diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..0e7f4ce --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,111 @@ +name: Build Python Dist + +on: + workflow_dispatch: + +jobs: + build-wheels: + name: Build wheels on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + - os: windows-latest + - os: macos-15 + deployment-target: '14.0' + - os: macos-15-intel + deployment-target: '13.0' + + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - name: Cache ITK build + uses: actions/cache@v5 + with: + path: ${{ github.workspace }}/itk-build + key: itk-5.4.5-${{ matrix.os }} + restore-keys: | + itk-5.4.5-${{ matrix.os }} + + - name: Build ITK (macOS) + if: runner.os == 'macOS' + run: | + git clone --depth 1 --branch v5.4.5 https://github.com/InsightSoftwareConsortium/ITK.git /tmp/ITK + if [ ! -f ${{ github.workspace }}/itk-build/ITKConfig.cmake ]; then + cmake -S /tmp/ITK -B ${{ github.workspace }}/itk-build -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF -DBUILD_SHARED_LIBS=OFF + cmake --build ${{ github.workspace }}/itk-build --parallel $(sysctl -n hw.ncpu) + fi + + - name: Build ITK (Windows) + if: runner.os == 'Windows' + shell: cmd + run: | + git clone --depth 1 --branch v5.4.5 https://github.com/InsightSoftwareConsortium/ITK.git C:\ITK_src + if not exist "${{ github.workspace }}\itk-build\ITKConfig.cmake" ( + cmake -S C:\ITK_src -B "${{ github.workspace }}\itk-build" -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -G "Visual Studio 17 2022" -A x64 + cmake --build "${{ github.workspace }}\itk-build" --config Release --parallel + ) + + - name: Build wheels + uses: pypa/cibuildwheel@v3.4.0 + env: + CIBW_BUILD: 'cp310-* cp311-* cp312-* cp313-* cp314-*' + CIBW_SKIP: '*-musllinux* *i686 *-win32' + CIBW_CONTAINER_ENGINE: "docker; create_args: --volume ${{ github.workspace }}/itk-build:/itk-build" + CIBW_BEFORE_ALL_LINUX: | + git clone --depth 1 --branch v5.4.5 https://github.com/InsightSoftwareConsortium/ITK.git /tmp/ITK + if [ ! -f /itk-build/ITKConfig.cmake ]; then + cmake -S /tmp/ITK -B /itk-build -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF -DBUILD_SHARED_LIBS=OFF + cmake --build /itk-build --parallel $(nproc) + fi + CIBW_ENVIRONMENT_LINUX: ITK_DIR=/itk-build + CIBW_ENVIRONMENT_MACOS: ITK_DIR=${{ github.workspace }}/itk-build MACOSX_DEPLOYMENT_TARGET=${{ matrix.deployment-target }} + CIBW_ENVIRONMENT_WINDOWS: ITK_DIR='${{ github.workspace }}\itk-build' SKBUILD_BUILD_DIR='D:\b' + + - uses: actions/upload-artifact@v6 + with: + name: wheels-${{ matrix.os }} + path: ./wheelhouse/*.whl + + build-sdist: + name: Build source distribution + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - uses: actions/setup-python@v6 + with: + python-version: '3.13' + + - name: Install build + run: pip install build + + - name: Build sdist + run: python -m build --sdist + + - uses: actions/upload-artifact@v6 + with: + name: sdist + path: dist/*.tar.gz + + publish: + name: Publish to PyPI + needs: [build-wheels, build-sdist] + runs-on: ubuntu-latest + if: startsWith(github.ref, 'refs/tags/') + steps: + - uses: actions/download-artifact@v8 + with: + path: dist + pattern: '{wheels-*,sdist}' + merge-multiple: true + + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + password: ${{ secrets.PYPI_TOKEN }} diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml deleted file mode 100644 index 2bf8fa7..0000000 --- a/.github/workflows/linux.yml +++ /dev/null @@ -1,99 +0,0 @@ -name: Linux Build - -on: - push: - branches: [ dev, itk_update ] - tags: - - '*' - pull_request: - branches: [ dev ] - workflow_dispatch: - -jobs: - build: - runs-on: ubuntu-latest - container: quay.io/pypa/manylinux_2_28_x86_64 - if: ${{ !contains(github.event.head_commit.message, '[skip ci]') }} - - steps: - - name: Checkout code - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Print github refs - run: | - echo "github.ref_name: ${{ github.ref_name }}" - echo "github.event.release.tag_name: ${{ github.event.release.tag_name }}" - echo "github.ref: ${{ github.ref }}" - - - name: Checkout submodules - run: | - git config --global --add safe.directory /__w/samseg/samseg - git submodule init - git submodule update - - - name: Download gcc 10 compilers - run: | - yum install -y gcc-toolset-10 - source /opt/rh/gcc-toolset-10/enable - gcc --version - g++ --version - - - name: Install CMake 3.31.6 and wget - run: | - yum install -y wget - wget https://github.com/Kitware/CMake/releases/download/v3.31.6/cmake-3.31.6-linux-x86_64.sh - chmod +x cmake-3.31.6-linux-x86_64.sh - ./cmake-3.31.6-linux-x86_64.sh --prefix=/usr/local --skip-license - ln -s /usr/local/bin/cmake /usr/bin/cmake - cmake --version - - - name: Build ITK - run: | - - source /opt/rh/gcc-toolset-10/enable - export CC=/opt/rh/gcc-toolset-10/root/usr/bin/gcc - export CXX=/opt/rh/gcc-toolset-10/root/usr/bin/g++ - - mkdir ITK-build - cd ITK-build - cmake \ - -DBUILD_SHARED_LIBS=OFF \ - -DBUILD_TESTING=OFF \ - -DBUILD_EXAMPLES=OFF \ - -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_INSTALL_PREFIX=../ITK-install \ - ../ITK - make install - cd .. - - - name: Build samseg and run tests - run: | - - source /opt/rh/gcc-toolset-10/enable - export CC=/opt/rh/gcc-toolset-10/root/usr/bin/gcc - export CXX=/opt/rh/gcc-toolset-10/root/usr/bin/g++ - - .github/workflows/linux_build.sh /opt/python/cp39-cp39/bin/python - .github/workflows/linux_build.sh /opt/python/cp310-cp310/bin/python - .github/workflows/linux_build.sh /opt/python/cp311-cp311/bin/python - .github/workflows/linux_build.sh /opt/python/cp312-cp312/bin/python - ls dist/*.whl | xargs -n1 auditwheel repair - env: - ITK_DIR: ITK-install - - - name: Upload artifact - uses: actions/upload-artifact@v4 - with: - name: linux-wheels - path: wheelhouse/*.whl - - - name: Upload to PyPI - if: startsWith(github.ref, 'refs/tags') - run: | - $PYTHON -m pip install twine - $PYTHON -m twine upload wheelhouse/*.whl -u __token__ -p "$PASSWORD" - env: - PASSWORD: ${{ secrets.PYPI_TOKEN }} - PYTHON: /opt/python/cp38-cp38/bin/python diff --git a/.github/workflows/linux_build.sh b/.github/workflows/linux_build.sh deleted file mode 100755 index 974b241..0000000 --- a/.github/workflows/linux_build.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash -e -# This is an auxiliary script to build and test SAMSEG wheels -PYTHON_PATH=$1 -$PYTHON_PATH -m pip wheel . -w ./dist --no-deps -$PYTHON_PATH -m pip install samseg -f dist/ -$PYTHON_PATH -m pip install pytest -$PYTHON_PATH -m pip install tensorflow -$PYTHON_PATH -m pytest samseg/tests -rm samseg/gems/*.so diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml deleted file mode 100644 index de0b84e..0000000 --- a/.github/workflows/macos.yml +++ /dev/null @@ -1,224 +0,0 @@ -name: MacOS Build - -on: - push: - branches: [ dev, itk_update ] - tags: - - '*' - pull_request: - branches: [ dev ] - workflow_dispatch: - -jobs: - build: - name: Build and upload artefact - strategy: - # max-parallel: 1 - matrix: - os: [macos-latest, macos-13] - python-version: ["3.9", "3.10", "3.11", "3.12"] - # os: [macos-13] - # python-version: ["3.10"] - - runs-on: ${{ matrix.os }} - - steps: - - name: Checkout code - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Set up python versions ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - - name: Detect if arm and set build variables - if: runner.arch == 'ARM64' || runner.arch == 'ARM64' - run: | - APPLE="ON" - echo "APPLE=${APPLE}" >> $GITHUB_ENV - APPLE_ARM64="ON" - echo "APPLE_ARM64=${APPLE_ARM64}" >> $GITHUB_ENV - MACOSX_DEPLOYMENT_TARGET="14.0" - echo "MACOSX_DEPLOYMENT_TARGET=${MACOSX_DEPLOYMENT_TARGET}" >> $GITHUB_ENV - _PYTHON_HOST_PLATFORM="macosx-14.0-arm64" - echo "_PYTHON_HOST_PLATFORM=${_PYTHON_HOST_PLATFORM}" >> $GITHUB_ENV - ARCHFLAGS="-arch arm64" - echo "ARCHFLAGS=${ARCHFLAGS=}" >> $GITHUB_ENV - PYTHON_VERSION_STR=$(python -c "import sys;print(f'cp{sys.version_info.major}{sys.version_info.minor}')") - echo "PYTHON_VERSION_STR=${PYTHON_VERSION_STR}" >> $GITHUB_ENV - CMAKE_OSX_ARCHITECTURES="arm64" - echo "CMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES}" >> $GITHUB_ENV - - - name: Detect if x64 and set build variables - if: runner.arch == 'x64' - run: | - APPLE="ON" - echo "APPLE=${APPLE}" >> $GITHUB_ENV - APPLE_ARM64="OFF" - echo "APPLE_ARM64=${APPLE_ARM64}" >> $GITHUB_ENV - MACOSX_DEPLOYMENT_TARGET="13.0" - echo "MACOSX_DEPLOYMENT_TARGET=${MACOSX_DEPLOYMENT_TARGET}" >> $GITHUB_ENV - _PYTHON_HOST_PLATFORM="macosx-13.0-x86_64" - echo "_PYTHON_HOST_PLATFORM=${_PYTHON_HOST_PLATFORM}" >> $GITHUB_ENV - ARCHFLAGS="-arch x86_64" - echo "ARCHFLAGS=${ARCHFLAGS=}" >> $GITHUB_ENV - PYTHON_VERSION_STR=$(python -c "import sys;print(f'cp{sys.version_info.major}{sys.version_info.minor}')") - echo "PYTHON_VERSION_STR=${PYTHON_VERSION_STR}" >> $GITHUB_ENV - CMAKE_OSX_ARCHITECTURES="x86_64" - echo "CMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES}" >> $GITHUB_ENV - - - name: Checkout submodules - run: | - git submodule init - git submodule update - - - name: Build zlib - run: | - git clone https://github.com/madler/zlib.git - mkdir zlib-build-${PYTHON_VERSION_STR}-${_PYTHON_HOST_PLATFORM} - cd zlib-build-${PYTHON_VERSION_STR}-${_PYTHON_HOST_PLATFORM} - cmake ../zlib -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../zlib-install-${PYTHON_VERSION_STR}-${_PYTHON_HOST_PLATFORM} - make install - cd .. - - - name: Build ITK - run: | - mkdir ITK-build-${PYTHON_VERSION_STR}-${_PYTHON_HOST_PLATFORM} - cd ITK-build-${PYTHON_VERSION_STR}-${_PYTHON_HOST_PLATFORM} - cmake \ - -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \ - -DITK_USE_SYSTEM_PNG=ON \ - -DBUILD_SHARED_LIBS=OFF \ - -DBUILD_TESTING=OFF \ - -DBUILD_EXAMPLES=OFF \ - -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_INSTALL_PREFIX=../ITK-install-${PYTHON_VERSION_STR}-${_PYTHON_HOST_PLATFORM} \ - ../ITK - make install - cd .. - - - name: Build samseg for python version ${{ matrix.python-version }} and test - run: | - python -m pip wheel . -w ./dist-${PYTHON_VERSION_STR}-${_PYTHON_HOST_PLATFORM} --no-deps --verbose - env: - ITK_DIR: ITK-install-${{ env.PYTHON_VERSION_STR }}-${{ env._PYTHON_HOST_PLATFORM }} - ZLIB_INCLUDE_DIR: zlib-install-${{ env.PYTHON_VERSION_STR }}-${{ env._PYTHON_HOST_PLATFORM }}/include - ZLIB_LIBRARY: zlib-install-${{ env.PYTHON_VERSION_STR }}-${{ env._PYTHON_HOST_PLATFORM }}/lib/libz.a - APPLE_ARM64: ${{ env.APPLE_ARM64 }} - APPLE: ${{ env.APPLE }} - MACOSX_DEPLOYMENT_TARGET: ${{ env.MACOSX_DEPLOYMENT_TARGET }} - _PYTHON_HOST_PLATFORM: ${{ env._PYTHON_HOST_PLATFORM }} - ARCHFLAGS: ${{ env.ARCHFLAGS }} - CMAKE_OSX_ARCHITECTURES: ${{ env.CMAKE_OSX_ARCHITECTURES }} - - - name: Upload artifact - uses: actions/upload-artifact@v4 - with: - name: macos-wheels-${{ env.PYTHON_VERSION_STR }}-${{ env._PYTHON_HOST_PLATFORM }} - path: dist-${{ env.PYTHON_VERSION_STR }}-${{ env._PYTHON_HOST_PLATFORM }}/*.whl - - test: - name: Test the wheel - needs: build - strategy: - # max-parallel: 1 - matrix: - os: [macos-latest, macos-13] - python-version: ["3.9", "3.10", "3.11", "3.12"] - # os: [macos-13] - # python-version: ["3.10"] - - runs-on: ${{ matrix.os }} - - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Python - set up ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - - name: Detect if arm and set wheel variables - if: runner.arch == 'ARM64' || runner.arch == 'ARM64' - run: | - _PYTHON_HOST_PLATFORM="macosx-14.0-arm64" - echo "_PYTHON_HOST_PLATFORM=${_PYTHON_HOST_PLATFORM}" >> $GITHUB_ENV - PYTHON_VERSION_STR=$(python -c "import sys;print(f'cp{sys.version_info.major}{sys.version_info.minor}')") - echo "PYTHON_VERSION_STR=${PYTHON_VERSION_STR}" >> $GITHUB_ENV - SAMSEG_TEST_PATH=${GITHUB_WORKSPACE}/samseg - echo "SAMSEG_TEST_PATH=${SAMSEG_TEST_PATH}" >> $GITHUB_ENV - - - name: Detect if x64 and set build variables - if: runner.arch == 'x64' - run: | - _PYTHON_HOST_PLATFORM="macosx-13.0-x86_64" - echo "_PYTHON_HOST_PLATFORM=${_PYTHON_HOST_PLATFORM}" >> $GITHUB_ENV - PYTHON_VERSION_STR=$(python -c "import sys;print(f'cp{sys.version_info.major}{sys.version_info.minor}')") - echo "PYTHON_VERSION_STR=${PYTHON_VERSION_STR}" >> $GITHUB_ENV - SAMSEG_TEST_PATH=${GITHUB_WORKSPACE}/samseg - echo "SAMSEG_TEST_PATH=${SAMSEG_TEST_PATH}" >> $GITHUB_ENV - - - name: Download artifact - uses: actions/download-artifact@v4 - with: - name: macos-wheels-${{ env.PYTHON_VERSION_STR }}-${{ env._PYTHON_HOST_PLATFORM }} - path: ${{ github.workspace }} - - - - name: Install the wheel and test dependencies - run: | - python -m pip install samseg*.whl - python -m pip install pytest - python -m pip install tensorflow - cd .. - python -c "import samseg" - python -m pytest --pyargs samseg.tests - - publish: - name: Publish the wheel - needs: test - strategy: - max-parallel: 1 - matrix: - os: [macos-latest, macos-13] - python-version: ["3.9", "3.10", "3.11", "3.12"] - - runs-on: ${{ matrix.os }} - if: startsWith(github.ref, 'refs/tags') - steps: - - name: Python - set up ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - - name: Detect if arm and set wheel variables - if: runner.arch == 'ARM64' || runner.arch == 'ARM64' - run: | - _PYTHON_HOST_PLATFORM="macosx-14.0-arm64" - echo "_PYTHON_HOST_PLATFORM=${_PYTHON_HOST_PLATFORM}" >> $GITHUB_ENV - PYTHON_VERSION_STR=$(python -c "import sys;print(f'cp{sys.version_info.major}{sys.version_info.minor}')") - echo "PYTHON_VERSION_STR=${PYTHON_VERSION_STR}" >> $GITHUB_ENV - - - name: Detect if x64 and set build variables - if: runner.arch == 'x64' - run: | - _PYTHON_HOST_PLATFORM="macosx-13.0-x86_64" - echo "_PYTHON_HOST_PLATFORM=${_PYTHON_HOST_PLATFORM}" >> $GITHUB_ENV - PYTHON_VERSION_STR=$(python -c "import sys;print(f'cp{sys.version_info.major}{sys.version_info.minor}')") - echo "PYTHON_VERSION_STR=${PYTHON_VERSION_STR}" >> $GITHUB_ENV - - - name: Download artifact - uses: actions/download-artifact@v4 - with: - name: macos-wheels-${{ env.PYTHON_VERSION_STR }}-${{ env._PYTHON_HOST_PLATFORM }} - path: ${{ github.workspace }} - - - name: Upload to PyPI - run: | - python -m pip install twine - python -m twine upload *.whl -u __token__ -p "$PASSWORD" - env: - PASSWORD: ${{ secrets.PYPI_TOKEN }} diff --git a/.github/workflows/macos_build.sh b/.github/workflows/macos_build.sh deleted file mode 100755 index 974b241..0000000 --- a/.github/workflows/macos_build.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash -e -# This is an auxiliary script to build and test SAMSEG wheels -PYTHON_PATH=$1 -$PYTHON_PATH -m pip wheel . -w ./dist --no-deps -$PYTHON_PATH -m pip install samseg -f dist/ -$PYTHON_PATH -m pip install pytest -$PYTHON_PATH -m pip install tensorflow -$PYTHON_PATH -m pytest samseg/tests -rm samseg/gems/*.so diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml deleted file mode 100644 index 2a9947f..0000000 --- a/.github/workflows/windows.yml +++ /dev/null @@ -1,124 +0,0 @@ -name: Windows Build -on: - push: - branches: [ dev, itk_update ] - tags: - - '*' - pull_request: - branches: [ dev ] - workflow_dispatch: - -jobs: - build: - name: Build, test and upload - strategy: - max-parallel: 1 - matrix: - python-version: ["3.9", "3.10", "3.11", "3.12"] - - runs-on: windows-2022 - - if: ${{ !contains(github.event.head_commit.message, '[skip ci]') }} - - steps: - - name: Checkout code - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Checkout submodules - run: | - git submodule init - git submodule update - - - name: Setup python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - architecture: 'x64' - - - name: Set python version - run: | - $pythonVersionStr = python -c "import sys; print(f'cp{sys.version_info.major}{sys.version_info.minor}')" - echo "pythonVersionStr=$pythonVersionStr" | Out-File -FilePath $Env:GITHUB_ENV -Encoding utf8 -Append - - - name: Build zlib - run: | - git clone --branch v1.3.1 --single-branch https://github.com/madler/zlib.git - md zlib-build - cd zlib-build - cmake ..\zlib -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="..\zlib-install" - cmake --build . --config Release --target install - cd .. - dir - - - name: Build ITK - run: | - md ITK-build - cd ITK-build - cmake.exe -G "Visual Studio 17 2022" -DBUILD_SHARED_LIBS=OFF -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF -DCMAKE_BUILD_TYPE=Release ..\ITK - cmake --build . --config Release --target Install - cd .. - shell: cmd - - - - name: Build wheel - run: | - python -m pip wheel . -w .\dist --no-deps --verbose - python -m pip install . -f .\dist\ - #python -m pip install -r requirements.txt - #python -m pip install pytest - #python -m pip install tensorflow - cd .. - python -c 'import samseg' - # python -m pytest samseg\samseg\tests - - rm samseg\gems\*.pyd - rm samseg\samseg\gems\Release\*.pyd - - env: - ZLIB_INCLUDE_DIR: .\zlib-install\include - ZLIB_LIBRARY: .\zlib-install\lib\zlibstatic.lib - ITK_DIR: ITK-build - - - name: Upload artifact - uses: actions/upload-artifact@v4 - with: - name: windows-wheels-${{ env.pythonVersionStr }} - path: .\dist\*.whl - - publish: - name: Publish the wheels - needs: build - strategy: - max-parallel: 1 - matrix: - python-version: ["3.8", "3.9", "3.10", "3.11"] - - runs-on: windows-2022 - if: startsWith(github.ref, 'refs/tags') - steps: - - name: Setup python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - architecture: 'x64' - - - name: Set python version - run: | - $pythonVersionStr = python -c "import sys; print(f'cp{sys.version_info.major}{sys.version_info.minor}')" - echo "pythonVersionStr=$pythonVersionStr" | Out-File -FilePath $Env:GITHUB_ENV -Encoding utf8 -Append - - - name: Download artifact - uses: actions/download-artifact@v4 - with: - name: windows-wheels-${{ env.pythonVersionStr }} - path: ${{ github.workspace }} - - - name: Upload to PyPI - if: ${{ github.event_name == 'push' && (startsWith(github.ref, 'refs/tags') || startsWith(env.GITHUB_REF, 'refs/tags')) }} - run: | - python -m pip install twine - python -m twine upload *.whl -u __token__ -p "$env:PASSWORD" - env: - PASSWORD: ${{ secrets.PYPI_TOKEN }} diff --git a/.gitignore b/.gitignore index 45dc0c7..d5f0ab3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,32 +1,86 @@ -CMakeCache.txt +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Linker files +*.ilk + +# Debugger Files +*.pdb + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll +*.so.* + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Build directories +build/ +Build/ +build-*/ + +# CMake generated files CMakeFiles/ -ITKIOFactoryRegistration/ -Matlab/CMakeFiles/ -Matlab/cmake_install.cmake -bin/ +CMakeCache.txt cmake_install.cmake -cuda/CMakeFiles/ -cuda/cmake_install.cmake +Makefile +install_manifest.txt +compile_commands.json + +# Temporary files +*.tmp +*.bak +*.swp + +# vcpkg +vcpkg_installed/ + +# Debug information files +*.dwo + +# Test output & cache +Testing/ +.cache/ + +# CUDA intermediate files +*.i +*.ii +*.gpu +*.ptx +*.cubin +*.fatbin # Byte-compiled / optimized / DLL files __pycache__/ -*.py[cod] +*.py[codz] *$py.class -# C extensions -*.so - -# Images and numpy files (for now) -*.nii -*.nii.gz -*.mgz -*.mgh -*.npy -*.npz - # Distribution / packaging .Python -build/ develop-eggs/ dist/ downloads/ @@ -45,8 +99,6 @@ share/python-wheels/ MANIFEST # PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec @@ -60,11 +112,10 @@ htmlcov/ .nox/ .coverage .coverage.* -.cache nosetests.xml coverage.xml *.cover -*.py,cover +*.py.cover .hypothesis/ .pytest_cache/ cover/ @@ -73,19 +124,6 @@ cover/ *.mo *.pot -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - # Sphinx documentation docs/_build/ @@ -100,45 +138,15 @@ target/ profile_default/ ipython_config.py -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -#poetry.lock - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -#pdm.lock -# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it -# in version control. -# https://pdm.fming.dev/#use-with-ide -.pdm.toml - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +# PEP 582 __pypackages__/ -# Celery stuff -celerybeat-schedule -celerybeat.pid - # SageMath parsed files *.sage.py # Environments .env +.envrc .venv env/ venv/ @@ -170,9 +178,18 @@ dmypy.json # Cython debug symbols cython_debug/ -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ +# Ruff +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# pdm +.pdm-python +.pdm-build/ + +# pixi +.pixi + +# Logs +*.log diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index aa973b9..0000000 --- a/.gitmodules +++ /dev/null @@ -1,8 +0,0 @@ -[submodule "ITK"] - path = ITK - url = https://github.com/InsightSoftwareConsortium/ITK.git - branch = release-4.13 -[submodule "pybind11"] - path = pybind11 - url = https://github.com/pybind/pybind11.git - branch = stable diff --git a/CMakeLists.txt b/CMakeLists.txt index 3c81d62..451772c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,108 +1,44 @@ -# project info -project(fs_python) -cmake_minimum_required(VERSION 3.9) -enable_language(C CXX) +cmake_minimum_required(VERSION 3.24) +project(samseg LANGUAGES C CXX) +include(FetchContent) -# prevent third-party packages from importing as a system, OP: no clue what this is -set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) - - -# set the default build type to 'Release' for optimization purposes -if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "No build type selected - defaulting to Release") set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Default build type" FORCE) endif() - -# -------------------------------------------------- -# external dependencies -# -------------------------------------------------- -set(pybind11_DIR $ENV{pybind11_DIR}) -if(NOT pybind11_DIR) - set(pydbind11_DIR "pybind11") -endif() - -# -------- itk -------- -find_package(ITK HINTS ${ITK_DIR} REQUIRED) - - - - -# enable std c++11 -set(CMAKE_CXX_STANDARD 11) - - -# -------------------------------------------------- -# setup python -# -------------------------------------------------- - -# initialize pybind for python wrapping -add_subdirectory(${pybind11_DIR} pybind11) -message(STATUS "ITK_DIR=${ITK_DIR} pybind11_DIR=${pybind11_DIR}") - - -# -------------------------------------------------- -# build settings -# -------------------------------------------------- -# set -DAPPLE=ON and -DAPPLE_ARM64=ON on cmake command line for arm64 build -# when building with freesurfer, CMAKE_C_COMPILER and CMAKE_CXX_COMPILER will be specified on the cmake command line -if(DEFINED ENV{APPLE}) - MESSAGE(STATUS "ARCH VARIABLE SET TO --[$ENV{APPLE_ARM64}]--") - if($ENV{APPLE_ARM64} MATCHES "ON") - MESSAGE(STATUS "SETTING TARGET TO ARM64") - set(CMAKE_OSX_ARCHITECTURES "arm64") - add_definitions(-DARM64 -DDarwin -DPNG_ARM_NEON_OPT=0) - else() - MESSAGE(STATUS "SETTING TARGET TO X86_64") - set(CMAKE_OSX_ARCHITECTURES "x86_64") - endif() -endif() - -message(STATUS "CMAKE_C_COMPILER=${CMAKE_C_COMPILER}, CMAKE_C_COMPILER_ID=${CMAKE_C_COMPILER_ID}, CMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}, CMAKE_CXX_COMPILER_ID=${CMAKE_CXX_COMPILER_ID}") - -# warnings -if(NOT DEFINED ENV{APPLE}) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Werror -Wno-absolute-value -Wno-sign-compare -Wno-write-strings -Wno-unused-result -Wno-unused-parameter") +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +option(PROFILING "Enable profiling with -pg" OFF) + +# Warning flags applied only to our own targets via INTERFACE library +# so that third-party dependencies (ITK, GDCM, etc.) are not affected. +add_library(samseg_warnings INTERFACE) +if(CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + target_compile_options(samseg_warnings INTERFACE + -Wall -Wextra + -Wno-sign-compare -Wno-unused-parameter + ) +elseif(MSVC) + target_compile_options(samseg_warnings INTERFACE /W3) endif() -# clang complains about -Wno-unused-but-set-variable and says to use -Wno-unused-const-variable -if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-non-c-typedef-for-linkage -Wno-unused-const-variable -Wno-inconsistent-missing-override -Wno-self-assign-field -Wno-tautological-overlap-compare -Wno-tautological-compare -Wno-unused-value -Wno-range-loop-analysis -Wno-return-stack-address -Wno-dangling-gsl") -else() - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-but-set-variable") +if(PROFILING AND NOT MSVC) + target_compile_options(samseg_warnings INTERFACE -pg) + target_link_options(samseg_warnings INTERFACE -pg) endif() -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") - -# linker options +# Binary size optimization flags, applied per-target via INTERFACE library +add_library(samseg_linkopt INTERFACE) if(APPLE) - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -dead_strip") - if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libgcc") - endif() -else() - set(STRIP_FLAGS "-fdata-sections -ffunction-sections -Wl,--gc-sections") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${STRIP_FLAGS}") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${STRIP_FLAGS} -Wl,-Map,ld_map.txt -Wl,--no-demangle") + target_link_options(samseg_linkopt INTERFACE -Wl,-dead_strip) +elseif(NOT WIN32) + target_compile_options(samseg_linkopt INTERFACE -fdata-sections -ffunction-sections) + target_link_options(samseg_linkopt INTERFACE -Wl,--gc-sections) endif() -if(PROFILING) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pg") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pg") -endif() - -message(STATUS "C/C++ standard set to ${CMAKE_CXX_STANDARD}, CMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}") -message(STATUS "For HOST_OS=${HOST_OS} CMAKE_CXX_COMPILER_ID=${CMAKE_CXX_COMPILER_ID}") -message(STATUS "For HOST_OS=${HOST_OS} CMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}") - -# -------------------------------------------------- -# build samseg -# -------------------------------------------------- - - -# build the gems library add_subdirectory(gems) - -#build python -add_subdirectory(samseg/cxx) +add_subdirectory(samseg/gems/_cxx) diff --git a/ITK b/ITK deleted file mode 160000 index 1fc47c7..0000000 --- a/ITK +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 1fc47c7bec4ee133318c1892b7b745763a17d411 diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index eaf1c9f..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,4 +0,0 @@ -graft samseg/atlas/* - -include versioneer.py -include samseg/_version.py diff --git a/gems/CMakeLists.txt b/gems/CMakeLists.txt index 52040ed..12e9088 100755 --- a/gems/CMakeLists.txt +++ b/gems/CMakeLists.txt @@ -1,18 +1,36 @@ -cmake_minimum_required(VERSION 3.5) -project(gems) - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}) -include_directories(interfaces) - -# find ITK if we're building independently of freesurfer +# ITK: try local install first, fetch from source if unavailable. +# FIND_PACKAGE_ARGS is not used here because ITK 5.4.x requires +# include(${ITK_USE_FILE}) for factory registration, which is only +# set by find_package — not by FetchContent's add_subdirectory path. +find_package(ITK 5.4.5 QUIET) if(NOT ITK_FOUND) + message(STATUS "ITK not found, fetching from source (v5.4.5)...") + FetchContent_Declare(ITK + GIT_REPOSITORY https://github.com/InsightSoftwareConsortium/ITK.git + GIT_TAG v5.4.5 + GIT_SHALLOW TRUE + ) + set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) + set(BUILD_TESTING OFF CACHE BOOL "" FORCE) + set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) + FetchContent_MakeAvailable(ITK) + set(ITK_DIR "${itk_BINARY_DIR}" CACHE PATH "" FORCE) find_package(ITK REQUIRED) endif() + +# UseITK.cmake handles factory registration and required compiler flags. +# Still required with ITK 5.4.x which does not export namespace targets. include(${ITK_USE_FILE}) -# same with zlib -if(NOT ZBLIB_FOUND) - find_package(ZLIB REQUIRED) +find_package(ZLIB QUIET) +if(NOT ZLIB_FOUND) + # ITK exports its bundled zlib-ng as a target named "zlib" + if(TARGET zlib) + set(ZLIB_LIBRARIES zlib) + message(STATUS "Using ITK's bundled zlib") + else() + message(FATAL_ERROR "ZLIB not found and ITK's bundled zlib is unavailable") + endif() endif() option(GEMS_BUILD_SHARED_LIBS "Build GEMS with shared libraries" OFF) @@ -20,7 +38,7 @@ option(GEMS_BUILD_EXECUTABLES "Build command line executables" OFF) option(GEMS_BUILD_TESTING "Build tests" OFF) option(GEMS_BUILD_GUI "Build GUI components (requires FLTK and VTK)" OFF) option(GEMS_BUILD_MATLAB "Build Matlab wrappers" OFF) -option(GEMS_BUILD_CUDA "Build CUDA stuff" OFF) +option(GEMS_BUILD_CUDA "Build CUDA support" OFF) option(GEMS_CROSS_THREAD_REPRODUCIBLE "Enable complete reproducibility" OFF) option(GEMS_USE_STATIC_ARRAY "Use array in TetrahedronInteriorConstIterator class" ON) @@ -29,57 +47,11 @@ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${GEMS_RUNTIME_PATH}) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${GEMS_RUNTIME_PATH}) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${GEMS_RUNTIME_PATH}) -set(CMAKE_CXX_STANDARD 11) -if(NOT APPLE_ARM64) - set(CMAKE_CXX_FLAGS "-fPIC -fpermissive -msse2 -mfpmath=sse") -endif() - -if(NOT WIN32) - # SC 2023/04/04: Commented out as it causes problem with Windows build - add_compile_options(-Wno-inconsistent-missing-override -Wno-self-assign-field) -endif() - -# to set additional debug cxxflags: -# export GEMS_DEBUG_CXXFLAG="-DGEMS_DEBUG_RASTERIZE_VOXEL_COUNT" -# touch CMakeLists.txt to trigger re-configuration -if(DEFINED ENV{GEMS_DEBUG_CXXFLAG}) - message(WARNING "additional gems debug cxxflags: $ENV{GEMS_DEBUG_CXXFLAG}") - add_compile_options($ENV{GEMS_DEBUG_CXXFLAG}) -endif() - -if(GEMS_USE_STATIC_ARRAY) - message(WARNING "compiling kvlGEMSCommon libraries with options -DUSING_STATIC_ARRAY -DMAX_LOADINGS=100") - add_definitions(-DUSING_STATIC_ARRAY -DMAX_LOADINGS=100) -endif() - -# PW 2022/02/25: No longer nessesary since we are now building 2 versions of -# the library: -# - kvlGEMSCommon -# - kvlGEMSCommon_dynmesh -##### -#if(GEMS_BUILD_EXECUTABLES OR GEMS_BUILD_GUI) -# add_definitions(-DUSE_DYNAMIC_MESH) -# message(WARNING "Since you're building executables to compute meshes, ITK dynamic meshes will" -# "be used (internally using std::map instead of std::vector to store lists of points, cells, etc)." -# "Everything will still work, but anything that only uses existing meshes will be" -# "slower than it could be (up to 100% slower)" -# ) -#endif() - if(GEMS_BUILD_CUDA) - find_package(CUDA REQUIRED) - set(CMAKE_CXX_FLAGS "-g ${CMAKE_CXX_FLAGS} -std=c++11") - include_directories(${CUDA_INCLUDE_DIRS}) - set(CMAKE_CXX_FLAGS "-DCUDA_FOUND ${CMAKE_CXX_FLAGS}") - include_directories(cuda) + enable_language(CUDA) add_subdirectory(cuda) endif() -if(GEMS_CROSS_THREAD_REPRODUCIBLE) - set(CMAKE_CXX_FLAGS "-DCROSS_THREAD_REPRODUCIBLE ${CMAKE_CXX_FLAGS}") -endif() - -# source set(SOURCES gzstream.C itkMGHImageIO.cxx @@ -120,82 +92,57 @@ set(SOURCES kvlAtlasMeshJacobianDeterminantDrawer.cxx ) -# PW this is strange.. I don't understand why `SOURCES_DYN` however when not included, -# kvlBuildAtlasMesh does not behave as it should when `-DUSE_DYNAMIC_MESH` is defined -set(SOURCES_DYN - gzstream.C - itkMGHImageIO.cxx - itkMGHImageIOFactory.cxx - kvlAtlasMeshAlphaDrawer.cxx - kvlAtlasMeshCollection.cxx - kvlAtlasMeshCollectionValidator.cxx - kvlAtlasMeshDeformationConjugateGradientOptimizer.cxx - kvlAtlasMeshDeformationFixedStepGradientDescentOptimizer.cxx - kvlAtlasMeshDeformationGradientDescentOptimizer.cxx - kvlAtlasMeshDeformationLBFGSOptimizer.cxx - kvlAtlasMeshDeformationOptimizer.cxx - kvlAtlasMeshLabelImageStatisticsCollector.cxx - kvlAtlasMeshMultiAlphaDrawer.cxx - kvlAtlasMeshPositionCostAndGradientCalculator.cxx - kvlAtlasMeshProbabilityImageStatisticsCollector.cxx - kvlAtlasMeshRasterizor.cxx - kvlAtlasMeshSmoother.cxx - kvlAtlasMeshStatisticsCollector.cxx - kvlAtlasMeshSummaryDrawer.cxx - kvlAtlasMeshToIntensityImageCostAndGradientCalculatorBase.cxx - kvlAtlasMeshToWishartGaussMixtureCostAndGradientCalculator.cxx - kvlAtlasMeshToFrobeniusGaussMixtureCostAndGradientCalculator.cxx - kvlAtlasMeshToDSWbetaGaussMixtureCostAndGradientCalculator.cxx - kvlAtlasMeshToIntensityImageCostAndGradientCalculator.cxx - kvlAtlasMeshToIntensityImageLogDomainCostAndGradientCalculator.cxx - kvlAtlasMeshToLabelImageCostAndGradientCalculator.cxx - kvlAtlasMeshToPointSetCostAndGradientCalculator.cxx - kvlAtlasMeshVisitCounter.cxx - kvlAtlasMeshValueDrawer.cxx - kvlAtlasParameterEstimator.cxx - kvlAverageAtlasMeshPositionCostAndGradientCalculator.cxx - kvlCompressionLookupTable.cxx - kvlConditionalGaussianEntropyCostAndGradientCalculator.cxx - kvlCroppedImageReader.cxx - kvlHistogrammer.cxx - kvlMutualInformationCostAndGradientCalculator.cxx - kvlAtlasMeshJacobianDeterminantDrawer.cxx -) - -message(WARNING "ZLIB_LIBRARIES=${ZLIB_LIBRARIES} ITK_LIBRARIES=${ITK_LIBRARIES}") +function(configure_gems_target target) + target_include_directories(${target} PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/interfaces + ${ITK_INCLUDE_DIRS} + ) + target_link_libraries(${target} + PRIVATE samseg_warnings samseg_linkopt ${ZLIB_LIBRARIES} + PUBLIC ${ITK_LIBRARIES} + ) + + if(DEFINED ENV{GEMS_DEBUG_CXXFLAG}) + message(WARNING "additional gems debug cxxflags: $ENV{GEMS_DEBUG_CXXFLAG}") + target_compile_options(${target} PRIVATE $ENV{GEMS_DEBUG_CXXFLAG}) + endif() + + if(GEMS_USE_STATIC_ARRAY) + target_compile_definitions(${target} PRIVATE USING_STATIC_ARRAY MAX_LOADINGS=100) + endif() + + if(GEMS_BUILD_CUDA) + target_compile_definitions(${target} PRIVATE CUDA_FOUND) + target_include_directories(${target} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/cuda) + target_link_libraries(${target} PRIVATE kvlGEMSCUDA) + endif() + + if(GEMS_CROSS_THREAD_REPRODUCIBLE) + target_compile_definitions(${target} PRIVATE CROSS_THREAD_REPRODUCIBLE) + endif() +endfunction() -# gems libary add_library(kvlGEMSCommon ${SOURCES}) -target_link_libraries(kvlGEMSCommon ${ZLIB_LIBRARIES} ${ITK_LIBRARIES}) - -# gems library with dynamic meshes. Needed for `kvlBuildAtlasMesh` but causes -# samseg to run slower, so only link against `kvlGEMSCommon_dynmesh` when nessesary. -add_library(kvlGEMSCommon_dynmesh ${SOURCES_DYN}) -target_compile_definitions(kvlGEMSCommon_dynmesh PRIVATE -DUSE_DYNAMIC_MESH) -target_link_libraries(kvlGEMSCommon_dynmesh ${ZLIB_LIBRARIES} ${ITK_LIBRARIES}) +configure_gems_target(kvlGEMSCommon) -## !!!BAD!!! both `kvlGEMSCommon_dynmesh` `kvlGEMSCommon` will have the same md5sum -## Useful for testing though -#add_definitions(-DUSE_DYNAMIC_MESH) -#add_library(kvlGEMSCommon_dynmesh ${SOURCES}) -#target_link_libraries(kvlGEMSCommon_dynmesh ${ITK_LIBRARIES} ${ZLIB_LIBRARIES}) +# Dynamic mesh variant is slower but required by kvlBuildAtlasMesh +add_library(kvlGEMSCommon_dynmesh ${SOURCES}) +target_compile_definitions(kvlGEMSCommon_dynmesh PRIVATE USE_DYNAMIC_MESH) +configure_gems_target(kvlGEMSCommon_dynmesh) -# build command line executables if(GEMS_BUILD_EXECUTABLES) add_subdirectory(Executables) endif() -# build tests if(GEMS_BUILD_TESTING) add_subdirectory(Testing) endif() -# build GUI if(GEMS_BUILD_GUI) add_subdirectory(GUI) endif() -# build Matlab wrappers if(GEMS_BUILD_MATLAB) add_subdirectory(Matlab) endif() diff --git a/gems/Executables/CMakeLists.txt b/gems/Executables/CMakeLists.txt index 7375e18..ec93ce3 100644 --- a/gems/Executables/CMakeLists.txt +++ b/gems/Executables/CMakeLists.txt @@ -1,53 +1,37 @@ option(GEMS_MAKE_SPARSE_INITIAL_MESHES "Make sparse initial meshes" ON) -include_directories(${FS_INCLUDE_DIRS}) # added for linking to FS - -if(MAKE_SPARSE_INITIAL_MESHES) +if(GEMS_MAKE_SPARSE_INITIAL_MESHES) message(WARNING "Since you're opting to make sparse (i.e., irregular) initial meshes, the TetGen library will be included, which has a restrictive license.") if(NOT Tetgen_FOUND) find_package(Tetgen REQUIRED) endif() - add_definitions(-DUSE_TETGEN) - include_directories(${Tetgen_INCLUDE_DIR}) endif() -add_executable(kvlBuildAtlasMesh - kvlBuildAtlasMesh.cxx - kvlAtlasMeshBuilder.cxx - kvlAtlasMeshCollectionFastReferencePositionCost.cxx - kvlAtlasMeshCollectionModelLikelihoodCalculator.cxx - kvlMultiResolutionAtlasMesher.cxx -) -add_executable(kvlBuildAtlasMesh.tetgen - kvlBuildAtlasMesh.cxx +set(ATLAS_BUILDER_SOURCES kvlAtlasMeshBuilder.cxx kvlAtlasMeshCollectionFastReferencePositionCost.cxx kvlAtlasMeshCollectionModelLikelihoodCalculator.cxx kvlMultiResolutionAtlasMesher.cxx ) -add_executable(samseg-atlas - samseg-atlas.cxx - kvlAtlasMeshBuilder.cxx - kvlAtlasMeshCollectionFastReferencePositionCost.cxx - kvlAtlasMeshCollectionModelLikelihoodCalculator.cxx - kvlMultiResolutionAtlasMesher.cxx -) -add_executable(samseg-atlas.tetgen - samseg-atlas.cxx - kvlAtlasMeshBuilder.cxx - kvlAtlasMeshCollectionFastReferencePositionCost.cxx - kvlAtlasMeshCollectionModelLikelihoodCalculator.cxx - kvlMultiResolutionAtlasMesher.cxx -) +add_executable(kvlBuildAtlasMesh kvlBuildAtlasMesh.cxx ${ATLAS_BUILDER_SOURCES}) +add_executable(kvlBuildAtlasMesh.tetgen kvlBuildAtlasMesh.cxx ${ATLAS_BUILDER_SOURCES}) +add_executable(samseg-atlas samseg-atlas.cxx ${ATLAS_BUILDER_SOURCES}) +add_executable(samseg-atlas.tetgen samseg-atlas.cxx ${ATLAS_BUILDER_SOURCES}) add_help(samseg-atlas samseg-atlas.help.xml) -add_definitions(-DUSE_DYNAMIC_MESH) -target_link_libraries(kvlBuildAtlasMesh kvlGEMSCommon_dynmesh utils) -target_link_libraries(kvlBuildAtlasMesh.tetgen kvlGEMSCommon_dynmesh utils) -target_link_libraries(samseg-atlas kvlGEMSCommon_dynmesh utils) -target_link_libraries(samseg-atlas.tetgen kvlGEMSCommon_dynmesh utils) -if(MAKE_SPARSE_INITIAL_MESHES) - target_link_libraries(kvlBuildAtlasMesh.tetgen samseg-atlas.tetgen ${Tetgen_LIBRARIES}) -endif() +set(ALL_EXECUTABLES kvlBuildAtlasMesh kvlBuildAtlasMesh.tetgen samseg-atlas samseg-atlas.tetgen) +foreach(exe IN LISTS ALL_EXECUTABLES) + target_compile_definitions(${exe} PRIVATE USE_DYNAMIC_MESH) + target_link_libraries(${exe} PRIVATE kvlGEMSCommon_dynmesh utils) +endforeach() +if(GEMS_MAKE_SPARSE_INITIAL_MESHES) + target_compile_definitions(kvlBuildAtlasMesh.tetgen PRIVATE USE_TETGEN) + target_include_directories(kvlBuildAtlasMesh.tetgen PRIVATE ${Tetgen_INCLUDE_DIR}) + target_link_libraries(kvlBuildAtlasMesh.tetgen PRIVATE ${Tetgen_LIBRARIES}) + + target_compile_definitions(samseg-atlas.tetgen PRIVATE USE_TETGEN) + target_include_directories(samseg-atlas.tetgen PRIVATE ${Tetgen_INCLUDE_DIR}) + target_link_libraries(samseg-atlas.tetgen PRIVATE ${Tetgen_LIBRARIES}) +endif() diff --git a/gems/GUI/CMakeLists.txt b/gems/GUI/CMakeLists.txt index d32b9ac..8bfeacc 100644 --- a/gems/GUI/CMakeLists.txt +++ b/gems/GUI/CMakeLists.txt @@ -1,41 +1,32 @@ -# FLTK is required find_package(FLTK REQUIRED) -include_directories(${FLTK_INCLUDE_DIR}) -# VTK as well if(NOT VTK_FOUND) find_package(VTK REQUIRED) include(${VTK_USE_FILE}) endif() -# FLTK's fluid generates C++ files in the build directory -include_directories(${GEMS_SOURCE_DIR}/GUI) -include_directories(${GEMS_BINARY_DIR}/GUI) - -# add libary add_library(kvlGEMSGUI vtkFlRenderWindowInteractor.cxx kvlImageViewer.cxx) +target_include_directories(kvlGEMSGUI PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_BINARY_DIR} + ${FLTK_INCLUDE_DIR} +) target_link_libraries(kvlGEMSGUI - ${ITK_LIBRARIES} - ${VTK_LIBRARIES} - ${FLTK_LIBRARIES} + PUBLIC ${ITK_LIBRARIES} ${VTK_LIBRARIES} ${FLTK_LIBRARIES} ) -# add an executable fltk_wrap_ui(kvlEstimateAtlasParameters kvlAtlasParameterEstimationConsoleGUI.fl) - add_executable(kvlEstimateAtlasParameters ${kvlEstimateAtlasParameters_FLTK_UI_SRCS} kvlEstimateAtlasParameters.cxx kvlAtlasParameterEstimationConsole.cxx ) -target_link_libraries(kvlEstimateAtlasParameters kvlGEMSCommon_dynmesh kvlGEMSGUI) +target_link_libraries(kvlEstimateAtlasParameters PRIVATE kvlGEMSCommon_dynmesh kvlGEMSGUI) -# add executable fltk_wrap_ui(kvlViewMeshCollectionWithGUI kvlAtlasMeshViewingConsoleGUI.fl) - add_executable(kvlViewMeshCollectionWithGUI ${kvlViewMeshCollectionWithGUI_FLTK_UI_SRCS} kvlViewMeshCollectionWithGUI.cxx kvlAtlasMeshViewingConsole.cxx ) -target_link_libraries(kvlViewMeshCollectionWithGUI kvlGEMSCommon_dynmesh kvlGEMSGUI) +target_link_libraries(kvlViewMeshCollectionWithGUI PRIVATE kvlGEMSCommon_dynmesh kvlGEMSGUI) diff --git a/gems/Matlab/CMakeLists.txt b/gems/Matlab/CMakeLists.txt index 1a73e1e..f272afe 100644 --- a/gems/Matlab/CMakeLists.txt +++ b/gems/Matlab/CMakeLists.txt @@ -1,253 +1,74 @@ find_package(Matlab REQUIRED) -# Build the mex file containing all the real functionality -MATLAB_ADD_MEX( NAME kvlGEMSMatlab - SRC kvlGEMSMatlab.cxx kvlMatlabRunnerArray.cxx kvlMatlabObjectArray.cxx - LINK_TO ${ITK_LIBRARIES} kvlGEMSCommon ) - - -# Copy some scripts -CONFIGURE_FILE( kvlReadCompressionLookupTable.m - ${GEMS_RUNTIME_PATH}/kvlReadCompressionLookupTable.m COPYONLY ) -CONFIGURE_FILE( kvlMergeAlphas.m - ${GEMS_RUNTIME_PATH}/kvlMergeAlphas.m COPYONLY ) -CONFIGURE_FILE( showImage.m - ${GEMS_RUNTIME_PATH}/showImage.m COPYONLY ) -CONFIGURE_FILE( kvlColorCodeProbabilityImages.m - ${GEMS_RUNTIME_PATH}/kvlColorCodeProbabilityImages.m COPYONLY ) -CONFIGURE_FILE( mosaicImages.m - ${GEMS_RUNTIME_PATH}/mosaicImages.m COPYONLY ) -CONFIGURE_FILE( kvlEvaluateMeshPositionInVectorFormat.m - ${GEMS_RUNTIME_PATH}/kvlEvaluateMeshPositionInVectorFormat.m COPYONLY ) -CONFIGURE_FILE( backprojectKroneckerProductBasisFunctions.m - ${GEMS_RUNTIME_PATH}/backprojectKroneckerProductBasisFunctions.m COPYONLY ) -CONFIGURE_FILE( computePrecisionOfKroneckerProductBasisFunctions.m - ${GEMS_RUNTIME_PATH}/computePrecisionOfKroneckerProductBasisFunctions.m COPYONLY ) -CONFIGURE_FILE( projectKroneckerProductBasisFunctions.m - ${GEMS_RUNTIME_PATH}/projectKroneckerProductBasisFunctions.m COPYONLY ) -CONFIGURE_FILE( kvlReadSharedGMMParameters.m - ${GEMS_RUNTIME_PATH}/kvlReadSharedGMMParameters.m COPYONLY ) -CONFIGURE_FILE( kvlReadCompressionLookupTable.m - ${GEMS_RUNTIME_PATH}/kvlReadCompressionLookupTable.m COPYONLY ) -CONFIGURE_FILE( kvlWriteCompressionLookupTable.m - ${GEMS_RUNTIME_PATH}/kvlWriteCompressionLookupTable.m COPYONLY ) -CONFIGURE_FILE( kvlWriteSharedGMMParameters.m - ${GEMS_RUNTIME_PATH}/kvlWriteSharedGMMParameters.m COPYONLY ) -CONFIGURE_FILE( kvlWarpMesh.m - ${GEMS_RUNTIME_PATH}/kvlWarpMesh.m COPYONLY ) -CONFIGURE_FILE( kvlFitRestrictedGMM.m - ${GEMS_RUNTIME_PATH}/kvlFitRestrictedGMM.m COPYONLY ) - - -# For each function, also create a .m file calling the mex file -# with the correct arguments. -SET( runnerName "GetImageBuffer" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "SetImageBuffer" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "ReadCroppedImage" ) -SET( runnerNumberOfOutputs "4" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "ReadMeshCollection" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "GetMesh" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "RasterizeAtlasMesh" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "SmoothImageBuffer" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "GetAlphasInMeshNodes" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "SetAlphasInMeshNodes" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "SmoothMeshCollection" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "ScaleMeshCollection" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "BiasFieldCorrectImage" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "WriteImage" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "CreateImage" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "DeformMesh" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "GetLevenbergMarquardtOptimizer" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "Clear" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "SetMaximumNumberOfThreads" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "ScaleMesh" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "SmoothMesh" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "ReadImage" ) -SET( runnerNumberOfOutputs "2" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "GetTransformMatrix" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "GetMeshNodePositions" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "SetMeshCollectionPositions" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "WriteMeshCollection" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "TransformMeshCollection" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "SetKOfMeshCollection" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "CreateTransform" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "EvaluateMeshPosition" ) -SET( runnerNumberOfOutputs "2" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "EvaluateMeshPositionWithEntropy" ) -SET( runnerNumberOfOutputs "2" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "SetMeshNodePositions" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "ChangeK" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "GetImageFromOptimizer" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "CreateRGBImage" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "WriteRGBImage" ) -SET( runnerNumberOfOutputs "0" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "GetCroppedRegion" ) -SET( runnerNumberOfOutputs "4" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "GetCostAndGradientCalculator" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "GetAverageAtlasMeshPositionCostAndGradientCalculator" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "GetOptimizer" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "StepOptimizer" ) -SET( runnerNumberOfOutputs "2" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "CreateMeshCollection" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - -SET( runnerName "DrawJacobianDeterminant" ) -SET( runnerNumberOfOutputs "1" ) -CONFIGURE_FILE( kvlRunnerWrapperTemplate.m - ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m ) - +matlab_add_mex(NAME kvlGEMSMatlab + SRC kvlGEMSMatlab.cxx kvlMatlabRunnerArray.cxx kvlMatlabObjectArray.cxx + LINK_TO ${ITK_LIBRARIES} kvlGEMSCommon +) + +configure_file(kvlReadCompressionLookupTable.m ${GEMS_RUNTIME_PATH}/kvlReadCompressionLookupTable.m COPYONLY) +configure_file(kvlMergeAlphas.m ${GEMS_RUNTIME_PATH}/kvlMergeAlphas.m COPYONLY) +configure_file(showImage.m ${GEMS_RUNTIME_PATH}/showImage.m COPYONLY) +configure_file(kvlColorCodeProbabilityImages.m ${GEMS_RUNTIME_PATH}/kvlColorCodeProbabilityImages.m COPYONLY) +configure_file(mosaicImages.m ${GEMS_RUNTIME_PATH}/mosaicImages.m COPYONLY) +configure_file(kvlEvaluateMeshPositionInVectorFormat.m ${GEMS_RUNTIME_PATH}/kvlEvaluateMeshPositionInVectorFormat.m COPYONLY) +configure_file(backprojectKroneckerProductBasisFunctions.m ${GEMS_RUNTIME_PATH}/backprojectKroneckerProductBasisFunctions.m COPYONLY) +configure_file(computePrecisionOfKroneckerProductBasisFunctions.m ${GEMS_RUNTIME_PATH}/computePrecisionOfKroneckerProductBasisFunctions.m COPYONLY) +configure_file(projectKroneckerProductBasisFunctions.m ${GEMS_RUNTIME_PATH}/projectKroneckerProductBasisFunctions.m COPYONLY) +configure_file(kvlReadSharedGMMParameters.m ${GEMS_RUNTIME_PATH}/kvlReadSharedGMMParameters.m COPYONLY) +configure_file(kvlReadCompressionLookupTable.m ${GEMS_RUNTIME_PATH}/kvlReadCompressionLookupTable.m COPYONLY) +configure_file(kvlWriteCompressionLookupTable.m ${GEMS_RUNTIME_PATH}/kvlWriteCompressionLookupTable.m COPYONLY) +configure_file(kvlWriteSharedGMMParameters.m ${GEMS_RUNTIME_PATH}/kvlWriteSharedGMMParameters.m COPYONLY) +configure_file(kvlWarpMesh.m ${GEMS_RUNTIME_PATH}/kvlWarpMesh.m COPYONLY) +configure_file(kvlFitRestrictedGMM.m ${GEMS_RUNTIME_PATH}/kvlFitRestrictedGMM.m COPYONLY) + +set(RUNNERS + GetImageBuffer:1 + SetImageBuffer:0 + ReadCroppedImage:4 + ReadMeshCollection:1 + GetMesh:1 + RasterizeAtlasMesh:1 + SmoothImageBuffer:1 + GetAlphasInMeshNodes:1 + SetAlphasInMeshNodes:0 + SmoothMeshCollection:1 + ScaleMeshCollection:0 + BiasFieldCorrectImage:1 + WriteImage:0 + CreateImage:1 + DeformMesh:1 + GetLevenbergMarquardtOptimizer:1 + Clear:0 + SetMaximumNumberOfThreads:0 + ScaleMesh:0 + SmoothMesh:0 + ReadImage:2 + GetTransformMatrix:1 + GetMeshNodePositions:1 + SetMeshCollectionPositions:0 + WriteMeshCollection:0 + TransformMeshCollection:0 + SetKOfMeshCollection:0 + CreateTransform:1 + EvaluateMeshPosition:2 + EvaluateMeshPositionWithEntropy:2 + SetMeshNodePositions:0 + ChangeK:0 + GetImageFromOptimizer:1 + CreateRGBImage:1 + WriteRGBImage:0 + GetCroppedRegion:4 + GetCostAndGradientCalculator:1 + GetAverageAtlasMeshPositionCostAndGradientCalculator:1 + GetOptimizer:1 + StepOptimizer:2 + CreateMeshCollection:1 + DrawJacobianDeterminant:1 +) + +foreach(runner IN LISTS RUNNERS) + string(REGEX MATCH "^([^:]+):([0-9]+)$" _ "${runner}") + set(runnerName "${CMAKE_MATCH_1}") + set(runnerNumberOfOutputs "${CMAKE_MATCH_2}") + configure_file(kvlRunnerWrapperTemplate.m ${GEMS_RUNTIME_PATH}/kvl${runnerName}.m) +endforeach() diff --git a/gems/Testing/CMakeLists.txt b/gems/Testing/CMakeLists.txt index 39e5239..cf044c1 100644 --- a/gems/Testing/CMakeLists.txt +++ b/gems/Testing/CMakeLists.txt @@ -1,56 +1,49 @@ set(Boost_USE_STATIC_LIBS ON) find_package(Boost 1.59.0) -if(Boost_FOUND) - include_directories(${Boost_INCLUDE_DIRS}) -endif() -# add an executable add_executable(kvlAtlasMeshRasterizorTestGPU kvlAtlasMeshRasterizorTestGPU.cxx) -target_link_libraries(kvlAtlasMeshRasterizorTestGPU kvlGEMSCommon) +target_link_libraries(kvlAtlasMeshRasterizorTestGPU PRIVATE kvlGEMSCommon) -# testCompressionLookupTable add_executable(testCompressionLookupTable testCompressionLookupTable.cxx) -target_link_libraries(testCompressionLookupTable kvlGEMSCommon) +target_link_libraries(testCompressionLookupTable PRIVATE kvlGEMSCommon) add_executable(testdeformMeshPython testdeformMeshPython.cxx) -target_link_libraries(testdeformMeshPython kvlGEMSCommon) +target_link_libraries(testdeformMeshPython PRIVATE kvlGEMSCommon) -# add_executable(testdeformMeshPython.dynmesh testdeformMeshPython.cxx) -target_compile_definitions(testdeformMeshPython.dynmesh PRIVATE -DUSE_DYNAMIC_MESH) -target_link_libraries(testdeformMeshPython.dynmesh kvlGEMSCommon_dynmesh) +target_compile_definitions(testdeformMeshPython.dynmesh PRIVATE USE_DYNAMIC_MESH) +target_link_libraries(testdeformMeshPython.dynmesh PRIVATE kvlGEMSCommon_dynmesh) -# boost tests if(Boost_FOUND) - set(GEMS2libs kvlGEMSCommon ) - set(testsrcs boosttests.cpp) - list(APPEND testsrcs testatlasmeshrasterizorbasic.cpp) - list(APPEND testsrcs atlasmeshvisitcountercpuwrapper.cpp) - list(APPEND testsrcs atlasmeshalphadrawercpuwrapper.cpp) - list(APPEND testsrcs testatlasmeshvisitcounter.cpp) - list(APPEND testsrcs testatlasmeshalphadrawer.cpp) - list(APPEND testsrcs teststopwatch.cpp) - - list(APPEND testsrcs imageutils.cpp) - - if(CUDA_FOUND) - list(APPEND testsrcs testcudaimage.cpp) - list(APPEND testsrcs cudaglobalfixture.cpp) - list(APPEND testsrcs cudaimagetests.cu) - list(APPEND testsrcs testcudatetrahedralmesh.cpp) - list(APPEND testsrcs testdimensioncuda.cpp) + set(GEMS2libs kvlGEMSCommon) + set(testsrcs + boosttests.cpp + testatlasmeshrasterizorbasic.cpp + atlasmeshvisitcountercpuwrapper.cpp + atlasmeshalphadrawercpuwrapper.cpp + testatlasmeshvisitcounter.cpp + testatlasmeshalphadrawer.cpp + teststopwatch.cpp + imageutils.cpp + ) + + if(GEMS_BUILD_CUDA) + list(APPEND testsrcs + testcudaimage.cpp + cudaglobalfixture.cpp + cudaimagetests.cu + testcudatetrahedralmesh.cpp + testdimensioncuda.cpp + ) list(APPEND GEMS2libs kvlGEMSCUDA) - cuda_add_executable( TestGEMS2 ${testsrcs} ${cudatestsrcs}) - else() - add_executable(TestGEMS2 ${testsrcs}) endif() - target_link_libraries(TestGEMS2 ${Boost_LIBRARIES} ${GEMS2libs}) + add_executable(TestGEMS2 ${testsrcs}) + target_link_libraries(TestGEMS2 PRIVATE ${Boost_LIBRARIES} ${GEMS2libs}) + target_include_directories(TestGEMS2 PRIVATE ${Boost_INCLUDE_DIRS}) endif() - -# copy some files + configure_file(test.nii ${GEMS_RUNTIME_PATH}/test.nii COPYONLY) configure_file(test.txt.gz ${GEMS_RUNTIME_PATH}/test.txt.gz COPYONLY) - configure_file(inp_image_deformmesh.mgz ${GEMS_RUNTIME_PATH}/inp_image_deformmesh.mgz COPYONLY) configure_file(atlas_level1_deformmesh.txt.gz ${GEMS_RUNTIME_PATH}/atlas_level1_deformmesh.txt.gz COPYONLY) diff --git a/gems/cuda/CMakeLists.txt b/gems/cuda/CMakeLists.txt index b986921..3d20ee9 100644 --- a/gems/cuda/CMakeLists.txt +++ b/gems/cuda/CMakeLists.txt @@ -1,10 +1,9 @@ -set(cudasrcs cudacontroller.cpp) - -list(APPEND cudasrcs atlasmeshvisitcountercuda.cpp) -list(APPEND cudasrcs visitcountersimplecudaimpl.cu) -list(APPEND cudasrcs visitcountertetrahedralmeshcudaimpl.cu) - -list(APPEND cudasrcs atlasmeshalphadrawercuda.cpp) -list(APPEND cudasrcs atlasmeshalphadrawercudaimpl.cu) - -cuda_add_library(kvlGEMSCUDA ${cudasrcs}) +add_library(kvlGEMSCUDA STATIC + cudacontroller.cpp + atlasmeshvisitcountercuda.cpp + visitcountersimplecudaimpl.cu + visitcountertetrahedralmeshcudaimpl.cu + atlasmeshalphadrawercuda.cpp + atlasmeshalphadrawercudaimpl.cu +) +target_include_directories(kvlGEMSCUDA PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/gems/fs_build_GEMS2 b/gems/fs_build_GEMS2 deleted file mode 100755 index 2ca7471..0000000 --- a/gems/fs_build_GEMS2 +++ /dev/null @@ -1,34 +0,0 @@ -#! /bin/bash -ef -set -eu - -export CC="`which cc`" -export CXX="`which c++`" -export AR="`which ar`" -export RANLIB="`which ranlib`" - -rm -Rf CMakeCache.txt CMakeFiles/ CMakeTmp/ - -cmake . -G "Unix Makefiles" \ --DBUILD_CUDA=OFF \ --DBUILD_EXECUTABLES=OFF \ --DBUILD_GUI=OFF \ --DBUILD_MATLAB=OFF \ --DBUILD_SHARED_LIBS=OFF \ --DBUILD_TESTING=OFF \ --DITK_DIR=../packages/itk/build \ --DCMAKE_BUILD_TYPE=Release \ --DCMAKE_CXX_COMPILER=$CXX \ --DCMAKE_CXX_COMPILER_AR=$AR \ --DCMAKE_CXX_COMPILER_RANLIB=$RANLIB \ --DCMAKE_CXX_FLAGS="-msse2 -mfpmath=sse -fPIC -fpermissive" \ --DCMAKE_C_COMPILER=$CC \ --DCMAKE_C_COMPILER_AR=$AR \ --DCMAKE_C_COMPILER_RANLIB=$RANLIB \ --DCMAKE_C_FLAGS="-msse2 -mfpmath=sse -fPIC -fpermissive" \ --DCMAKE_VERBOSE_MAKEFILE=ON \ --DCMAKE_INSTALL_PREFIX=. - -make clean -make -j 8 -#make test -#make install diff --git a/gems/itkMGHImageIO.cxx b/gems/itkMGHImageIO.cxx index 13c1d20..7d9435f 100755 --- a/gems/itkMGHImageIO.cxx +++ b/gems/itkMGHImageIO.cxx @@ -608,16 +608,7 @@ namespace itk case SHORT: returnValue = sizeof(short); break; case INT: returnValue = sizeof(int); break; case FLOAT: returnValue = sizeof(float); break; - - // DJ -- added this in to get the compiler to shut up - case UNKNOWNCOMPONENTTYPE: - case CHAR: - case USHORT: - case UINT: - case ULONG: - case LONG: - case DOUBLE: - break; + default: break; } return returnValue; } diff --git a/gems/itkMGHImageIO.h b/gems/itkMGHImageIO.h index ad92ebe..37330ed 100755 --- a/gems/itkMGHImageIO.h +++ b/gems/itkMGHImageIO.h @@ -66,24 +66,24 @@ namespace itk /**--------------- Read the data----------------- **/ - virtual bool CanReadFile(const char* FileNameToRead); + bool CanReadFile(const char* FileNameToRead) override; /* Set the spacing and dimension information for the set file name */ - virtual void ReadImageInformation(); + void ReadImageInformation() override; /* Read the data from the disk into provided memory buffer */ - virtual void Read(void* buffer); - + void Read(void* buffer) override; + /**---------------Write the data------------------**/ - - virtual bool CanWriteFile(const char* FileNameToWrite); + + bool CanWriteFile(const char* FileNameToWrite) override; /* Set the spacing and dimension information for the set file name */ - virtual void WriteImageInformation(); + void WriteImageInformation() override; /* Write the data to the disk from the provided memory buffer */ - virtual void Write(const void* buffer); + void Write(const void* buffer) override; protected: MGHImageIO(); ~MGHImageIO(); - void PrintSelf(std::ostream& os, Indent indent) const; + void PrintSelf(std::ostream& os, Indent indent) const override; void ReadVolumeHeader(gzFile fp); @@ -102,7 +102,7 @@ namespace itk void PermuteFrameValues(const void* buffer, char* tempmemory); - unsigned int GetComponentSize() const; + unsigned int GetComponentSize() const override; }; // end class declaration @@ -142,15 +142,7 @@ namespace itk writer.Write( fs::MRI_FLOAT ); break; case SHORT: writer.Write( fs::MRI_SHORT ); break; - - // DJ -- added these cases to make the compiler shut up - case UNKNOWNCOMPONENTTYPE: - case CHAR: - case UINT: - case ULONG: - case LONG: - break; - + default: break; } // dof !?! -> default value = 1 diff --git a/gems/itkMGHImageIOFactory.h b/gems/itkMGHImageIOFactory.h index d5b3b94..08c6adf 100755 --- a/gems/itkMGHImageIOFactory.h +++ b/gems/itkMGHImageIOFactory.h @@ -18,8 +18,8 @@ namespace itk typedef SmartPointer ConstPointer; /** Class methods used to interface with the registered factories **/ - virtual const char* GetITKSourceVersion(void) const; - virtual const char* GetDescription(void) const; + const char* GetITKSourceVersion(void) const override; + const char* GetDescription(void) const override; /** Method for class instantiation **/ itkFactorylessNewMacro(Self); diff --git a/gems/kvlAtlasMeshAlphaDrawer.h b/gems/kvlAtlasMeshAlphaDrawer.h index a94479a..9a57e4f 100755 --- a/gems/kvlAtlasMeshAlphaDrawer.h +++ b/gems/kvlAtlasMeshAlphaDrawer.h @@ -53,9 +53,9 @@ public : virtual ~AtlasMeshAlphaDrawer(); // - bool RasterizeTetrahedron( const AtlasMesh* mesh, + bool RasterizeTetrahedron( const AtlasMesh* mesh, AtlasMesh::CellIdentifier tetrahedronId, - int threadNumber ); + int threadNumber ) override; private: AtlasMeshAlphaDrawer(const Self&); //purposely not implemented diff --git a/gems/kvlAtlasMeshCollection.cxx b/gems/kvlAtlasMeshCollection.cxx index 76a63f4..19b6c9c 100755 --- a/gems/kvlAtlasMeshCollection.cxx +++ b/gems/kvlAtlasMeshCollection.cxx @@ -2014,7 +2014,6 @@ ::GetRegionGrown( AtlasMesh::CellIdentifier seedId, unsigned int radius, bool ma const AtlasMesh::CellType* cell = m_Cells->ElementAt( *neighborIt ); // Create a new cell of the correct type - typedef itk::VertexCell< AtlasMesh::CellType > VertexCell; typedef itk::LineCell< AtlasMesh::CellType > LineCell; typedef itk::TriangleCell< AtlasMesh::CellType > TriangleCell; typedef itk::TetrahedronCell< AtlasMesh::CellType > TetrahedronCell; diff --git a/gems/kvlAtlasMeshCollection.h b/gems/kvlAtlasMeshCollection.h index e2ac3b7..6fe664b 100755 --- a/gems/kvlAtlasMeshCollection.h +++ b/gems/kvlAtlasMeshCollection.h @@ -162,9 +162,9 @@ protected : virtual ~AtlasMeshCollection(); // Print - void PrintSelf( std::ostream& os, itk::Indent indent ) const; + void PrintSelf( std::ostream& os, itk::Indent indent ) const override; - // + // AtlasMeshCollection::Pointer GetEdgeSplitted( AtlasMesh::CellIdentifier edgeId, AtlasMesh::CellIdentifier newVertexId, AtlasMesh::PointIdentifier newPointId, diff --git a/gems/kvlAtlasMeshCollectionValidator.h b/gems/kvlAtlasMeshCollectionValidator.h index 9e83958..2faa03f 100755 --- a/gems/kvlAtlasMeshCollectionValidator.h +++ b/gems/kvlAtlasMeshCollectionValidator.h @@ -35,10 +35,10 @@ protected : virtual ~AtlasMeshCollectionValidator(); // Print - void PrintSelf( std::ostream& os, itk::Indent indent ) const; + void PrintSelf( std::ostream& os, itk::Indent indent ) const override; + - private : AtlasMeshCollectionValidator(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/gems/kvlAtlasMeshDeformationConjugateGradientOptimizer.h b/gems/kvlAtlasMeshDeformationConjugateGradientOptimizer.h index 48e6ee3..f269548 100755 --- a/gems/kvlAtlasMeshDeformationConjugateGradientOptimizer.h +++ b/gems/kvlAtlasMeshDeformationConjugateGradientOptimizer.h @@ -29,10 +29,10 @@ public : AtlasMeshDeformationConjugateGradientOptimizer(); virtual ~AtlasMeshDeformationConjugateGradientOptimizer(); - void Initialize(); + void Initialize() override; + + double FindAndOptimizeNewSearchDirection() override; - double FindAndOptimizeNewSearchDirection(); - private: AtlasMeshDeformationConjugateGradientOptimizer(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/gems/kvlAtlasMeshDeformationFixedStepGradientDescentOptimizer.cxx b/gems/kvlAtlasMeshDeformationFixedStepGradientDescentOptimizer.cxx index c9e5ab7..b8946de 100755 --- a/gems/kvlAtlasMeshDeformationFixedStepGradientDescentOptimizer.cxx +++ b/gems/kvlAtlasMeshDeformationFixedStepGradientDescentOptimizer.cxx @@ -1,5 +1,6 @@ #include "kvlAtlasMeshDeformationFixedStepGradientDescentOptimizer.h" +#include namespace kvl { @@ -63,7 +64,7 @@ ::FindAndOptimizeNewSearchDirection() std::cout << "trialCost: " << trialCost << std::endl; } if ( ( trialCost > m_Cost ) || - ( ( fabsf( m_Cost - trialCost ) / fabsf( trialCost ) ) < m_LineSearchStopCriterion ) ) + ( ( std::abs( m_Cost - trialCost ) / std::abs( trialCost ) ) < m_LineSearchStopCriterion ) ) { // Bad or insufficiently good step -- give up return 0.0; diff --git a/gems/kvlAtlasMeshDeformationFixedStepGradientDescentOptimizer.h b/gems/kvlAtlasMeshDeformationFixedStepGradientDescentOptimizer.h index c71f1b2..9c83181 100755 --- a/gems/kvlAtlasMeshDeformationFixedStepGradientDescentOptimizer.h +++ b/gems/kvlAtlasMeshDeformationFixedStepGradientDescentOptimizer.h @@ -41,8 +41,8 @@ public : AtlasMeshDeformationFixedStepGradientDescentOptimizer(); virtual ~AtlasMeshDeformationFixedStepGradientDescentOptimizer(); - double FindAndOptimizeNewSearchDirection(); - + double FindAndOptimizeNewSearchDirection() override; + private: AtlasMeshDeformationFixedStepGradientDescentOptimizer(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/gems/kvlAtlasMeshDeformationGradientDescentOptimizer.h b/gems/kvlAtlasMeshDeformationGradientDescentOptimizer.h index cc470e2..a71ed3b 100755 --- a/gems/kvlAtlasMeshDeformationGradientDescentOptimizer.h +++ b/gems/kvlAtlasMeshDeformationGradientDescentOptimizer.h @@ -29,10 +29,10 @@ public : AtlasMeshDeformationGradientDescentOptimizer(); virtual ~AtlasMeshDeformationGradientDescentOptimizer(); - void Initialize(); + void Initialize() override; + + double FindAndOptimizeNewSearchDirection() override; - double FindAndOptimizeNewSearchDirection(); - private: AtlasMeshDeformationGradientDescentOptimizer(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/gems/kvlAtlasMeshDeformationLBFGSOptimizer.h b/gems/kvlAtlasMeshDeformationLBFGSOptimizer.h index 1f9c526..193f7eb 100755 --- a/gems/kvlAtlasMeshDeformationLBFGSOptimizer.h +++ b/gems/kvlAtlasMeshDeformationLBFGSOptimizer.h @@ -41,10 +41,10 @@ public : AtlasMeshDeformationLBFGSOptimizer(); virtual ~AtlasMeshDeformationLBFGSOptimizer(); - void WipeMemory(); + void WipeMemory() override; + + double FindAndOptimizeNewSearchDirection() override; - double FindAndOptimizeNewSearchDirection(); - private: AtlasMeshDeformationLBFGSOptimizer(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/gems/kvlAtlasMeshDeformationOptimizer.cxx b/gems/kvlAtlasMeshDeformationOptimizer.cxx index 2ed696e..bc3b5dc 100755 --- a/gems/kvlAtlasMeshDeformationOptimizer.cxx +++ b/gems/kvlAtlasMeshDeformationOptimizer.cxx @@ -1,5 +1,6 @@ #include "kvlAtlasMeshDeformationOptimizer.h" +#include namespace kvl { @@ -430,7 +431,7 @@ ::DoLineSearch( const AtlasMesh::PointsContainer* startPosition, break; } - if ( fabsf( directionalDerivative ) <= ( -c2 * initialDirectionalDerivative ) ) + if ( std::abs( directionalDerivative ) <= ( -c2 * initialDirectionalDerivative ) ) { // Found an excellent solution that we can simply return -- no need for zooming newPosition = position; @@ -772,7 +773,7 @@ ::DoLineSearch( const AtlasMesh::PointsContainer* startPosition, // Check size - if ( ( fabsf( highAlpha - lowAlpha ) * maximalDeformationOfSearchDirection ) + if ( ( std::abs( highAlpha - lowAlpha ) * maximalDeformationOfSearchDirection ) < m_LineSearchMaximalDeformationIntervalStopCriterion ) { //std::cout << "!!!!!!!!!!!!!!!" << startPosition->Begin().Value() << std::endl; diff --git a/gems/kvlAtlasMeshJacobianDeterminantDrawer.h b/gems/kvlAtlasMeshJacobianDeterminantDrawer.h index 97e2233..7de3153 100755 --- a/gems/kvlAtlasMeshJacobianDeterminantDrawer.h +++ b/gems/kvlAtlasMeshJacobianDeterminantDrawer.h @@ -47,9 +47,9 @@ public : virtual ~AtlasMeshJacobianDeterminantDrawer(); // - bool RasterizeTetrahedron( const AtlasMesh* mesh, + bool RasterizeTetrahedron( const AtlasMesh* mesh, AtlasMesh::CellIdentifier tetrahedronId, - int threadNumber ); + int threadNumber ) override; private: AtlasMeshJacobianDeterminantDrawer(const Self&); //purposely not implemented diff --git a/gems/kvlAtlasMeshLabelImageStatisticsCollector.h b/gems/kvlAtlasMeshLabelImageStatisticsCollector.h index d3242e0..44ce375 100755 --- a/gems/kvlAtlasMeshLabelImageStatisticsCollector.h +++ b/gems/kvlAtlasMeshLabelImageStatisticsCollector.h @@ -49,7 +49,7 @@ public : AtlasAlphasType& statisticsInVertex0, AtlasAlphasType& statisticsInVertex1, AtlasAlphasType& statisticsInVertex2, - AtlasAlphasType& statisticsInVertex3 ); + AtlasAlphasType& statisticsInVertex3 ) override; private: diff --git a/gems/kvlAtlasMeshMultiAlphaDrawer.h b/gems/kvlAtlasMeshMultiAlphaDrawer.h index d13b94d..c35a5db 100755 --- a/gems/kvlAtlasMeshMultiAlphaDrawer.h +++ b/gems/kvlAtlasMeshMultiAlphaDrawer.h @@ -41,17 +41,17 @@ public : { return m_Image; } // - void Rasterize( const AtlasMesh* mesh ); + void Rasterize( const AtlasMesh* mesh ) override; + - protected: AtlasMeshMultiAlphaDrawer(); virtual ~AtlasMeshMultiAlphaDrawer(); - + // - bool RasterizeTetrahedron( const AtlasMesh* mesh, + bool RasterizeTetrahedron( const AtlasMesh* mesh, AtlasMesh::CellIdentifier tetrahedronId, - int threadNumber ); + int threadNumber ) override; private: AtlasMeshMultiAlphaDrawer(const Self&); //purposely not implemented diff --git a/gems/kvlAtlasMeshPositionCostAndGradientCalculator.h b/gems/kvlAtlasMeshPositionCostAndGradientCalculator.h index d144ade..b79e6a0 100755 --- a/gems/kvlAtlasMeshPositionCostAndGradientCalculator.h +++ b/gems/kvlAtlasMeshPositionCostAndGradientCalculator.h @@ -73,8 +73,8 @@ public : } /** */ - void Rasterize( const AtlasMesh* mesh ); - + void Rasterize( const AtlasMesh* mesh ) override; + /** Boundary conditions applied to gradient */ enum BoundaryConditionType { NONE, SLIDING, AFFINE, TRANSLATION }; void SetBoundaryCondition( const BoundaryConditionType& boundaryCondition ) @@ -127,10 +127,10 @@ public : virtual ~AtlasMeshPositionCostAndGradientCalculator(); // - bool RasterizeTetrahedron( const AtlasMesh* mesh, + bool RasterizeTetrahedron( const AtlasMesh* mesh, AtlasMesh::CellIdentifier tetrahedronId, - int threadNumber ); - + int threadNumber ) override; + virtual void AddDataContributionOfTetrahedron( const AtlasMesh::PointType& p0, const AtlasMesh::PointType& p1, const AtlasMesh::PointType& p2, diff --git a/gems/kvlAtlasMeshProbabilityImageStatisticsCollector.h b/gems/kvlAtlasMeshProbabilityImageStatisticsCollector.h index 2bb12c7..5743c0d 100755 --- a/gems/kvlAtlasMeshProbabilityImageStatisticsCollector.h +++ b/gems/kvlAtlasMeshProbabilityImageStatisticsCollector.h @@ -51,8 +51,8 @@ public : AtlasAlphasType& statisticsInVertex0, AtlasAlphasType& statisticsInVertex1, AtlasAlphasType& statisticsInVertex2, - AtlasAlphasType& statisticsInVertex3 ); - + AtlasAlphasType& statisticsInVertex3 ) override; + private: AtlasMeshProbabilityImageStatisticsCollector(const Self&); //purposely not implemented diff --git a/gems/kvlAtlasMeshSmoother.cxx b/gems/kvlAtlasMeshSmoother.cxx index d1c0214..3467f86 100755 --- a/gems/kvlAtlasMeshSmoother.cxx +++ b/gems/kvlAtlasMeshSmoother.cxx @@ -197,15 +197,13 @@ ::GetSmoothedMeshCollection() // // Get unnormalized counts - double cost = 0.0; m_MeshCollection->FlattenAlphas(); // Initialization to flat alphas for ( int iterationNumber = 0; iterationNumber < 10; iterationNumber++ ) { - AtlasMeshProbabilityImageStatisticsCollector::Pointer statisticsCollector = + AtlasMeshProbabilityImageStatisticsCollector::Pointer statisticsCollector = AtlasMeshProbabilityImageStatisticsCollector::New(); statisticsCollector->SetProbabilityImage( smoothedAlphasImage ); statisticsCollector->Rasterize( m_MeshCollection->GetReferenceMesh() ); - cost = statisticsCollector->GetMinLogLikelihood(); //std::cout << " EM iteration " << iterationNumber << " -> " << cost << std::endl; diff --git a/gems/kvlAtlasMeshSmoother.h b/gems/kvlAtlasMeshSmoother.h index c9dc28a..b098af3 100755 --- a/gems/kvlAtlasMeshSmoother.h +++ b/gems/kvlAtlasMeshSmoother.h @@ -65,10 +65,10 @@ protected : virtual ~AtlasMeshSmoother(); // Print - void PrintSelf( std::ostream& os, itk::Indent indent ) const; + void PrintSelf( std::ostream& os, itk::Indent indent ) const override; + - private : AtlasMeshSmoother(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/gems/kvlAtlasMeshStatisticsCollector.h b/gems/kvlAtlasMeshStatisticsCollector.h index 725aa8d..b00b14a 100755 --- a/gems/kvlAtlasMeshStatisticsCollector.h +++ b/gems/kvlAtlasMeshStatisticsCollector.h @@ -39,17 +39,17 @@ public : } /** */ - void Rasterize( const AtlasMesh* mesh ); - - + void Rasterize( const AtlasMesh* mesh ) override; + + protected: AtlasMeshStatisticsCollector(); virtual ~AtlasMeshStatisticsCollector(); - + // - bool RasterizeTetrahedron( const AtlasMesh* mesh, + bool RasterizeTetrahedron( const AtlasMesh* mesh, AtlasMesh::CellIdentifier tetrahedronId, - int threadNumber ); + int threadNumber ) override; virtual void GetContributionOfTetrahedron( const AtlasMesh::PointType& p0, const AtlasMesh::PointType& p1, diff --git a/gems/kvlAtlasMeshSummaryDrawer.h b/gems/kvlAtlasMeshSummaryDrawer.h index 5b07977..d4a6366 100755 --- a/gems/kvlAtlasMeshSummaryDrawer.h +++ b/gems/kvlAtlasMeshSummaryDrawer.h @@ -55,9 +55,9 @@ public : virtual ~AtlasMeshSummaryDrawer(); // - bool RasterizeTetrahedron( const AtlasMesh* mesh, + bool RasterizeTetrahedron( const AtlasMesh* mesh, AtlasMesh::CellIdentifier tetrahedronId, - int threadNumber ); + int threadNumber ) override; private: AtlasMeshSummaryDrawer(const Self&); //purposely not implemented diff --git a/gems/kvlAtlasMeshToDSWbetaGaussMixtureCostAndGradientCalculator.cxx b/gems/kvlAtlasMeshToDSWbetaGaussMixtureCostAndGradientCalculator.cxx index 83d0106..80b5a66 100644 --- a/gems/kvlAtlasMeshToDSWbetaGaussMixtureCostAndGradientCalculator.cxx +++ b/gems/kvlAtlasMeshToDSWbetaGaussMixtureCostAndGradientCalculator.cxx @@ -173,7 +173,7 @@ ::AddDataContributionOfTetrahedron( const AtlasMesh::PointType& p0, for ( ; !gmm_it.IsAtEnd(); ++gmm_it) { // Skip voxels for which nothing is known - if ( gmm_it.Value().Size() == 0 | fmm_it.Value().Size() == 0) + if ( gmm_it.Value().Size() == 0 || fmm_it.Value().Size() == 0) { //std::cout << "Skipping: " << it.Value().Size() << std::endl; ++fmm_it; @@ -231,9 +231,9 @@ ::AddDataContributionOfTetrahedron( const AtlasMesh::PointType& p0, zGradientBasis += weightNextSlice*exp(mixturelog-maxExponent); } - if (weightInterpolated!=fmm_it.GetExtraLoadingInterpolatedValue( classNumber ) | - weightNextRow!=fmm_it.GetExtraLoadingNextRowAddition( classNumber )| - weightNextColumn!=fmm_it.GetExtraLoadingNextColumnAddition( classNumber )| + if (weightInterpolated!=fmm_it.GetExtraLoadingInterpolatedValue( classNumber ) || + weightNextRow!=fmm_it.GetExtraLoadingNextRowAddition( classNumber )|| + weightNextColumn!=fmm_it.GetExtraLoadingNextColumnAddition( classNumber )|| weightNextSlice!=fmm_it.GetExtraLoadingNextSliceAddition( classNumber ) ) { std::cout<<"classNumber= "< + #if ITK_VERSION_MAJOR >= 5 #include #endif @@ -147,7 +149,7 @@ ::Estimate( bool verbose ) m_IterationNumber = 0; this->InvokeEvent( itk::StartEvent() ); while ( ( ( ( previousMinLogLikelihoodTimesPrior - m_CurrentMinLogLikelihoodTimesPrior ) / - fabsf( m_CurrentMinLogLikelihoodTimesPrior ) ) > m_StopCriterion ) && + std::abs( m_CurrentMinLogLikelihoodTimesPrior ) ) > m_StopCriterion ) && ( m_IterationNumber < m_MaximumNumberOfIterations ) ) { // Estimate alphas @@ -213,7 +215,7 @@ ::EstimateAlphas() double currentCost = previousCost / 2; m_AlphasEstimationIterationNumber = 0; this->InvokeEvent( AlphasEstimationStartEvent() ); - while ( ( ( ( previousCost - currentCost ) / fabsf( currentCost ) ) > m_AlphaEstimationStopCriterion ) && + while ( ( ( ( previousCost - currentCost ) / std::abs( currentCost ) ) > m_AlphaEstimationStopCriterion ) && ( m_AlphasEstimationIterationNumber < m_AlphasEstimationMaximumNumberOfIterations ) ) { previousCost = currentCost; diff --git a/gems/kvlAtlasParameterEstimator.h b/gems/kvlAtlasParameterEstimator.h index 2fdf5b1..33072e4 100755 --- a/gems/kvlAtlasParameterEstimator.h +++ b/gems/kvlAtlasParameterEstimator.h @@ -166,8 +166,8 @@ protected : virtual ~AtlasParameterEstimator(); // Print - void PrintSelf( std::ostream& os, itk::Indent indent ) const; - + void PrintSelf( std::ostream& os, itk::Indent indent ) const override; + // virtual void EstimateAlphas(); diff --git a/gems/kvlAverageAtlasMeshPositionCostAndGradientCalculator.h b/gems/kvlAverageAtlasMeshPositionCostAndGradientCalculator.h index 8800c13..0550883 100755 --- a/gems/kvlAverageAtlasMeshPositionCostAndGradientCalculator.h +++ b/gems/kvlAverageAtlasMeshPositionCostAndGradientCalculator.h @@ -34,8 +34,8 @@ public : } // - void Rasterize( const AtlasMesh* mesh ); - + void Rasterize( const AtlasMesh* mesh ) override; + protected: AverageAtlasMeshPositionCostAndGradientCalculator(); virtual ~AverageAtlasMeshPositionCostAndGradientCalculator(); diff --git a/gems/kvlCompressionLookupTable.cxx b/gems/kvlCompressionLookupTable.cxx index d0b7014..1273319 100755 --- a/gems/kvlCompressionLookupTable.cxx +++ b/gems/kvlCompressionLookupTable.cxx @@ -68,7 +68,6 @@ ::ReadCollapsedLabelFile() const std::cout << "Reading collapsedLabelFile: " << collapsedLabelFile << std::endl; std::string line; - unsigned short comp, lab; while ( std::getline( clfs, line ) ) { std::ostringstream inputParserStream; diff --git a/gems/kvlCompressionLookupTable.h b/gems/kvlCompressionLookupTable.h index e51088b..d8bfc4e 100755 --- a/gems/kvlCompressionLookupTable.h +++ b/gems/kvlCompressionLookupTable.h @@ -70,7 +70,7 @@ public : return m_LabelStringLookupTable.find( classNumber )->second; } - const int GetNumberOfClasses() const + int GetNumberOfClasses() const { return m_NumberOfClasses; } @@ -84,7 +84,7 @@ protected : virtual ~CompressionLookupTable(); // Print - void PrintSelf( std::ostream& os, itk::Indent indent ) const; + void PrintSelf( std::ostream& os, itk::Indent indent ) const override; // void FillInMissingNamesAndColors(); diff --git a/gems/kvlConditionalGaussianEntropyCostAndGradientCalculator.h b/gems/kvlConditionalGaussianEntropyCostAndGradientCalculator.h index 1d11f50..fe1f401 100755 --- a/gems/kvlConditionalGaussianEntropyCostAndGradientCalculator.h +++ b/gems/kvlConditionalGaussianEntropyCostAndGradientCalculator.h @@ -139,18 +139,18 @@ public : void SetImage( const ImageType* image ); /** */ - void Rasterize( const AtlasMesh* mesh ); - - + void Rasterize( const AtlasMesh* mesh ) override; + + protected: ConditionalGaussianEntropyCostAndGradientCalculator(); virtual ~ConditionalGaussianEntropyCostAndGradientCalculator(); // - bool RasterizeTetrahedron( const AtlasMesh* mesh, + bool RasterizeTetrahedron( const AtlasMesh* mesh, AtlasMesh::CellIdentifier tetrahedronId, - int threadNumber ); - + int threadNumber ) override; + private: ConditionalGaussianEntropyCostAndGradientCalculator(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/gems/kvlDSWbetaMMLikelihoodImageFilter.h b/gems/kvlDSWbetaMMLikelihoodImageFilter.h index b89f8c9..c60da40 100644 --- a/gems/kvlDSWbetaMMLikelihoodImageFilter.h +++ b/gems/kvlDSWbetaMMLikelihoodImageFilter.h @@ -71,9 +71,9 @@ class DSWbetaMMLikelihoodImageFilter : protected: DSWbetaMMLikelihoodImageFilter(); - virtual void BeforeThreadedGenerateData(); + void BeforeThreadedGenerateData() override; - virtual void ThreadedGenerateData(const RegionType & outputRegionForThread, itk::ThreadIdType); + void ThreadedGenerateData(const RegionType & outputRegionForThread, itk::ThreadIdType) override; private: DSWbetaMMLikelihoodImageFilter(const Self &); diff --git a/gems/kvlDSWbetaMMLikelihoodImageFilter.hxx b/gems/kvlDSWbetaMMLikelihoodImageFilter.hxx index 1f586a8..0dc909a 100644 --- a/gems/kvlDSWbetaMMLikelihoodImageFilter.hxx +++ b/gems/kvlDSWbetaMMLikelihoodImageFilter.hxx @@ -202,7 +202,6 @@ DSWbetaMMLikelihoodImageFilter< TInputImage > //std::cout << "Executing GMMLikelihoodImageFilter::ThreadedGenerateData()" << std::endl; // - const int numberOfDSWbeta = m_Concentrations.size(); const int numberOfClasses = m_NumberOfDSWbetaPerClass.size(); const int numberOfContrasts = this->GetNumberOfIndexedInputs(); // std::cout << "numberOfGaussians: " << numberOfGaussians << std::endl; diff --git a/gems/kvlFrobMMLikelihoodImageFilter.h b/gems/kvlFrobMMLikelihoodImageFilter.h index 303fe7b..ef5e54f 100644 --- a/gems/kvlFrobMMLikelihoodImageFilter.h +++ b/gems/kvlFrobMMLikelihoodImageFilter.h @@ -68,9 +68,9 @@ class FrobMMLikelihoodImageFilter : protected: FrobMMLikelihoodImageFilter(); - virtual void BeforeThreadedGenerateData(); + void BeforeThreadedGenerateData() override; - virtual void ThreadedGenerateData(const RegionType & outputRegionForThread, itk::ThreadIdType); + void ThreadedGenerateData(const RegionType & outputRegionForThread, itk::ThreadIdType) override; private: FrobMMLikelihoodImageFilter(const Self &); diff --git a/gems/kvlFrobMMLikelihoodImageFilter.hxx b/gems/kvlFrobMMLikelihoodImageFilter.hxx index ea941a5..cd137ba 100644 --- a/gems/kvlFrobMMLikelihoodImageFilter.hxx +++ b/gems/kvlFrobMMLikelihoodImageFilter.hxx @@ -190,7 +190,6 @@ FrobMMLikelihoodImageFilter< TInputImage > //std::cout << "Executing GMMLikelihoodImageFilter::ThreadedGenerateData()" << std::endl; // - const int numberOfFrobenius = m_Precisions.size(); const int numberOfClasses = m_NumberOfFrobeniusPerClass.size(); const int numberOfContrasts = this->GetNumberOfIndexedInputs(); // std::cout << "numberOfGaussians: " << numberOfGaussians << std::endl; diff --git a/gems/kvlGMMLikelihoodImageFilter.h b/gems/kvlGMMLikelihoodImageFilter.h index be2744a..c3a361e 100644 --- a/gems/kvlGMMLikelihoodImageFilter.h +++ b/gems/kvlGMMLikelihoodImageFilter.h @@ -54,10 +54,10 @@ class GMMLikelihoodImageFilter: protected: GMMLikelihoodImageFilter(); - virtual void BeforeThreadedGenerateData(); + void BeforeThreadedGenerateData() override; virtual void BeforeThreadedGenerateData(const RegionType region); - virtual void ThreadedGenerateData(const RegionType & outputRegionForThread, itk::ThreadIdType); + void ThreadedGenerateData(const RegionType & outputRegionForThread, itk::ThreadIdType) override; private: GMMLikelihoodImageFilter(const Self &); diff --git a/gems/kvlGMMLikelihoodImageFilter.hxx b/gems/kvlGMMLikelihoodImageFilter.hxx index daec95d..2ef2d26 100644 --- a/gems/kvlGMMLikelihoodImageFilter.hxx +++ b/gems/kvlGMMLikelihoodImageFilter.hxx @@ -254,7 +254,6 @@ GMMLikelihoodImageFilter< TInputImage > //std::cout << "Executing GMMLikelihoodImageFilter::ThreadedGenerateData()" << std::endl; // - const int numberOfGaussians = m_Means.size(); const int numberOfClasses = m_NumberOfGaussiansPerClass.size(); const int numberOfContrasts = this->GetNumberOfIndexedInputs(); // std::cout << "numberOfGaussians: " << numberOfGaussians << std::endl; diff --git a/gems/kvlHistogrammer.h b/gems/kvlHistogrammer.h index 6caec90..48add30 100755 --- a/gems/kvlHistogrammer.h +++ b/gems/kvlHistogrammer.h @@ -90,18 +90,18 @@ public : } /** */ - void Rasterize( const AtlasMesh* mesh ); - - + void Rasterize( const AtlasMesh* mesh ) override; + + protected: Histogrammer(); virtual ~Histogrammer(); - + // - bool RasterizeTetrahedron( const AtlasMesh* mesh, + bool RasterizeTetrahedron( const AtlasMesh* mesh, AtlasMesh::CellIdentifier tetrahedronId, - int threadNumber ); - + int threadNumber ) override; + private: Histogrammer(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/gems/kvlMutualInformationCostAndGradientCalculator.h b/gems/kvlMutualInformationCostAndGradientCalculator.h index 7621214..a21ce73 100755 --- a/gems/kvlMutualInformationCostAndGradientCalculator.h +++ b/gems/kvlMutualInformationCostAndGradientCalculator.h @@ -52,13 +52,13 @@ public : void SetImage( const ImageType* image ); /** */ - void Rasterize( const AtlasMesh* mesh ); - - + void Rasterize( const AtlasMesh* mesh ) override; + + protected: MutualInformationCostAndGradientCalculator(); virtual ~MutualInformationCostAndGradientCalculator(); - + void AddDataContributionOfTetrahedron( const AtlasMesh::PointType& p0, const AtlasMesh::PointType& p1, const AtlasMesh::PointType& p2, @@ -71,8 +71,8 @@ public : AtlasPositionGradientThreadAccumType& gradientInVertex0, AtlasPositionGradientThreadAccumType& gradientInVertex1, AtlasPositionGradientThreadAccumType& gradientInVertex2, - AtlasPositionGradientThreadAccumType& gradientInVertex3 ); - + AtlasPositionGradientThreadAccumType& gradientInVertex3 ) override; + private: MutualInformationCostAndGradientCalculator(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/gems/kvlRegisterImages.h b/gems/kvlRegisterImages.h index f773079..e5cd638 100644 --- a/gems/kvlRegisterImages.h +++ b/gems/kvlRegisterImages.h @@ -96,9 +96,6 @@ class RegistrationInterfaceCommand : public itk::Command // is a registration method. Then we ask for the optimizer object // from the registration method. auto registration = static_cast(object); - auto optimizer = - static_cast(registration->GetModifiableOptimizer()); - unsigned int currentLevel = registration->GetCurrentLevel(); typename RegistrationType::ShrinkFactorsPerDimensionContainerType shrinkFactors = registration->GetShrinkFactorsPerDimension(currentLevel); diff --git a/gems/kvlTetrahedronInteriorConstIterator.hxx b/gems/kvlTetrahedronInteriorConstIterator.hxx index 5f8a838..3d21762 100644 --- a/gems/kvlTetrahedronInteriorConstIterator.hxx +++ b/gems/kvlTetrahedronInteriorConstIterator.hxx @@ -44,9 +44,7 @@ TetrahedronInteriorConstIterator< TPixel > typedef typename ImageType::RegionType RegionType; typedef typename RegionType::IndexType IndexType; typedef typename IndexType::IndexValueType IndexValueType; - typedef typename RegionType::SizeType SizeType; - typedef typename SizeType::SizeValueType SizeValueType; - + // Compute the coordinates of the lower corner of the bounding box around the tetradron PointType lowerCorner = p0; for ( int i = 0; i < 3; i++ ) diff --git a/gems/kvlWMMLikelihoodImageFilter.h b/gems/kvlWMMLikelihoodImageFilter.h index 06aa902..78f5dda 100644 --- a/gems/kvlWMMLikelihoodImageFilter.h +++ b/gems/kvlWMMLikelihoodImageFilter.h @@ -68,9 +68,9 @@ class WMMLikelihoodImageFilter : protected: WMMLikelihoodImageFilter(); - virtual void BeforeThreadedGenerateData(); + void BeforeThreadedGenerateData() override; - virtual void ThreadedGenerateData(const RegionType & outputRegionForThread, itk::ThreadIdType); + void ThreadedGenerateData(const RegionType & outputRegionForThread, itk::ThreadIdType) override; private: WMMLikelihoodImageFilter(const Self &); diff --git a/gems/kvlWMMLikelihoodImageFilter.hxx b/gems/kvlWMMLikelihoodImageFilter.hxx index c28b010..1e4d398 100644 --- a/gems/kvlWMMLikelihoodImageFilter.hxx +++ b/gems/kvlWMMLikelihoodImageFilter.hxx @@ -232,7 +232,6 @@ WMMLikelihoodImageFilter< TInputImage > //std::cout << "Executing GMMLikelihoodImageFilter::ThreadedGenerateData()" << std::endl; // - const int numberOfWisharts = m_degreesOfFreedomExponent.size(); const int numberOfClasses = m_NumberOfWishartsPerClass.size(); const int numberOfContrasts = this->GetNumberOfIndexedInputs(); // std::cout << "numberOfGaussians: " << numberOfGaussians << std::endl; diff --git a/pybind11 b/pybind11 deleted file mode 160000 index a2e59f0..0000000 --- a/pybind11 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit a2e59f0e7065404b44dfe92a28aca47ba1378dc4 diff --git a/pyproject.toml b/pyproject.toml index ca4413f..f75bae9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,54 @@ [build-system] -requires = ["setuptools>=67", "wheel", "build", "versioneer"] -build-backend = "setuptools.build_meta" +requires = ["scikit-build-core>=0.10", "pybind11"] +build-backend = "scikit_build_core.build" + +[project] +name = "samseg" +dynamic = ["version"] +description = "Sequence-Adaptive Multimodal SEGmentation (SAMSEG)" +readme = "README.md" +license = {text = "MIT"} +requires-python = ">=3.9" +authors = [ + {name = "Koen Van Leemput"}, + {name = "Oula Puonti"}, + {name = "Juan Eugenio Iglesias"}, + {name = "Stefano Cerri"}, +] +classifiers = [ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", +] +dependencies = [ + "surfa @ git+https://github.com/freesurfer/surfa.git@master", + "scikit-learn", + "numpy", + "numba", +] + +[tool.scikit-build] +wheel.exclude = ["samseg/gems/_cxx"] + +[project.optional-dependencies] +test = ["pytest", "tensorflow"] + +[project.scripts] +run_samseg = "samseg.cli.run_samseg:main" +computeTissueConcentrations = "samseg.cli.computeTissueConcentrations:main" +prepareAtlasDirectory = "samseg.cli.prepareAtlasDirectory:main" +run_samseg_long = "samseg.cli.run_samseg_long:main" +segment_subregions = "samseg.cli.segment_subregions:main" +sbtiv = "samseg.cli.sbtiv:main" +gems_compute_atlas_probs = "samseg.cli.gems_compute_atlas_probs:main" +merge_add_mesh_alphas = "samseg.cli.merge_add_mesh_alphas:main" + +[project.urls] +Homepage = "https://github.com/freesurfer/samseg" + +[tool.scikit-build.metadata.version] +provider = "scikit_build_core.metadata.regex" +input = "samseg/__init__.py" + +[tool.scikit-build.cmake.define] +GEMS_BUILD_CUDA = {env = "GEMS_BUILD_CUDA", default = "OFF"} diff --git a/samseg/__init__.py b/samseg/__init__.py index 390ba03..e9461a8 100644 --- a/samseg/__init__.py +++ b/samseg/__init__.py @@ -16,5 +16,4 @@ # from .SamsegLongitudinalLesion import SamsegLongitudinalLesion from .figures import initVisualizer -from . import _version -__version__ = _version.get_versions()['version'] +__version__ = "0.5a" diff --git a/samseg/_version.py b/samseg/_version.py deleted file mode 100644 index 1af7152..0000000 --- a/samseg/_version.py +++ /dev/null @@ -1,658 +0,0 @@ - -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. -# Generated by versioneer-0.28 -# https://github.com/python-versioneer/python-versioneer - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys -from typing import Callable, Dict -import functools - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "$Format:%d$" - git_full = "$Format:%H$" - git_date = "$Format:%ci$" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "pep440" - cfg.tag_prefix = "" - cfg.parentdir_prefix = "" - cfg.versionfile_source = "samseg/_version.py" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, process.returncode - return stdout, process.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver): - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces): - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%d" % (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for _ in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} diff --git a/samseg/cxx/CMakeLists.txt b/samseg/cxx/CMakeLists.txt deleted file mode 100644 index 584c219..0000000 --- a/samseg/cxx/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -include_directories(${CMAKE_SOURCE_DIR}/gems ${CMAKE_CURRENT_SOURCE_DIR}) -include(${ITK_USE_FILE}) - -if(NOT APPLE_ARM64) - set(CMAKE_CXX_FLAGS "-fPIC -fpermissive -msse2 -mfpmath=sse") -endif() - -# temporary fix so that -g doesn't produce linker errors when binding cxx/python code -set(CMAKE_CXX_FLAGS_DEBUG "") -set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "") - -# SC 2023/04/04: Commented out as it causes problem with Windows build -# add_compile_options(-Wno-inconsistent-missing-override -Wno-self-assign-field) - -pybind11_add_module(gemsbindings - module.cxx - pyKvlCalculator.cxx - pyKvlImage.cxx - pyKvlMesh.cxx - pyKvlOptimizer.cxx - pyKvlTransform.cxx - pyKvlRigidRegistration.cxx - pyKvlAffineRegistration.cxx -) - -# link utilities -target_link_libraries(gemsbindings PRIVATE kvlGEMSCommon) - -# make sure the bindings library gets built into the repository even in out-of-source builds -set_target_properties(gemsbindings PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/samseg/gems) diff --git a/samseg/cxx/Makefile b/samseg/cxx/Makefile deleted file mode 100644 index 903cea6..0000000 --- a/samseg/cxx/Makefile +++ /dev/null @@ -1,317 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.20 - -# Default target executed when no arguments are given to make. -default_target: all -.PHONY : default_target - -# Allow only one "make -f Makefile2" at a time, but pass parallelism. -.NOTPARALLEL: - -#============================================================================= -# Special targets provided by cmake. - -# Disable implicit rules so canonical targets will work. -.SUFFIXES: - -# Disable VCS-based implicit rules. -% : %,v - -# Disable VCS-based implicit rules. -% : RCS/% - -# Disable VCS-based implicit rules. -% : RCS/%,v - -# Disable VCS-based implicit rules. -% : SCCS/s.% - -# Disable VCS-based implicit rules. -% : s.% - -.SUFFIXES: .hpux_make_needs_suffix_list - -# Command-line flag to silence nested $(MAKE). -$(VERBOSE)MAKESILENT = -s - -#Suppress display of executed commands. -$(VERBOSE).SILENT: - -# A target that is always out of date. -cmake_force: -.PHONY : cmake_force - -#============================================================================= -# Set environment variables for the build. - -# The shell in which to execute make rules. -SHELL = /bin/sh - -# The CMake executable. -CMAKE_COMMAND = /usr/bin/cmake - -# The command to remove a file. -RM = /usr/bin/cmake -E rm -f - -# Escaping for special characters. -EQUALS = = - -# The top-level source directory on which CMake was run. -CMAKE_SOURCE_DIR = /homes/9/op035/rauma_op035/software/samseg_python - -# The top-level build directory on which CMake was run. -CMAKE_BINARY_DIR = /homes/9/op035/rauma_op035/software/samseg_python - -#============================================================================= -# Targets provided globally by CMake. - -# Special rule for the target rebuild_cache -rebuild_cache: - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." - /usr/bin/cmake --regenerate-during-build -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) -.PHONY : rebuild_cache - -# Special rule for the target rebuild_cache -rebuild_cache/fast: rebuild_cache -.PHONY : rebuild_cache/fast - -# Special rule for the target edit_cache -edit_cache: - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..." - /usr/bin/ccmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) -.PHONY : edit_cache - -# Special rule for the target edit_cache -edit_cache/fast: edit_cache -.PHONY : edit_cache/fast - -# The main all target -all: cmake_check_build_system - cd /homes/9/op035/rauma_op035/software/samseg_python && $(CMAKE_COMMAND) -E cmake_progress_start /homes/9/op035/rauma_op035/software/samseg_python/CMakeFiles /homes/9/op035/rauma_op035/software/samseg_python/samseg/cxx//CMakeFiles/progress.marks - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 samseg/cxx/all - $(CMAKE_COMMAND) -E cmake_progress_start /homes/9/op035/rauma_op035/software/samseg_python/CMakeFiles 0 -.PHONY : all - -# The main clean target -clean: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 samseg/cxx/clean -.PHONY : clean - -# The main clean target -clean/fast: clean -.PHONY : clean/fast - -# Prepare targets for installation. -preinstall: all - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 samseg/cxx/preinstall -.PHONY : preinstall - -# Prepare targets for installation. -preinstall/fast: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 samseg/cxx/preinstall -.PHONY : preinstall/fast - -# clear depends -depend: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 -.PHONY : depend - -# Convenience name for target. -samseg/cxx/CMakeFiles/gemsbindings.dir/rule: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 samseg/cxx/CMakeFiles/gemsbindings.dir/rule -.PHONY : samseg/cxx/CMakeFiles/gemsbindings.dir/rule - -# Convenience name for target. -gemsbindings: samseg/cxx/CMakeFiles/gemsbindings.dir/rule -.PHONY : gemsbindings - -# fast build rule for target. -gemsbindings/fast: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/build -.PHONY : gemsbindings/fast - -module.o: module.cxx.o -.PHONY : module.o - -# target to build an object file -module.cxx.o: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/module.cxx.o -.PHONY : module.cxx.o - -module.i: module.cxx.i -.PHONY : module.i - -# target to preprocess a source file -module.cxx.i: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/module.cxx.i -.PHONY : module.cxx.i - -module.s: module.cxx.s -.PHONY : module.s - -# target to generate assembly for a file -module.cxx.s: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/module.cxx.s -.PHONY : module.cxx.s - -pyKvlCalculator.o: pyKvlCalculator.cxx.o -.PHONY : pyKvlCalculator.o - -# target to build an object file -pyKvlCalculator.cxx.o: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlCalculator.cxx.o -.PHONY : pyKvlCalculator.cxx.o - -pyKvlCalculator.i: pyKvlCalculator.cxx.i -.PHONY : pyKvlCalculator.i - -# target to preprocess a source file -pyKvlCalculator.cxx.i: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlCalculator.cxx.i -.PHONY : pyKvlCalculator.cxx.i - -pyKvlCalculator.s: pyKvlCalculator.cxx.s -.PHONY : pyKvlCalculator.s - -# target to generate assembly for a file -pyKvlCalculator.cxx.s: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlCalculator.cxx.s -.PHONY : pyKvlCalculator.cxx.s - -pyKvlImage.o: pyKvlImage.cxx.o -.PHONY : pyKvlImage.o - -# target to build an object file -pyKvlImage.cxx.o: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlImage.cxx.o -.PHONY : pyKvlImage.cxx.o - -pyKvlImage.i: pyKvlImage.cxx.i -.PHONY : pyKvlImage.i - -# target to preprocess a source file -pyKvlImage.cxx.i: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlImage.cxx.i -.PHONY : pyKvlImage.cxx.i - -pyKvlImage.s: pyKvlImage.cxx.s -.PHONY : pyKvlImage.s - -# target to generate assembly for a file -pyKvlImage.cxx.s: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlImage.cxx.s -.PHONY : pyKvlImage.cxx.s - -pyKvlMesh.o: pyKvlMesh.cxx.o -.PHONY : pyKvlMesh.o - -# target to build an object file -pyKvlMesh.cxx.o: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlMesh.cxx.o -.PHONY : pyKvlMesh.cxx.o - -pyKvlMesh.i: pyKvlMesh.cxx.i -.PHONY : pyKvlMesh.i - -# target to preprocess a source file -pyKvlMesh.cxx.i: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlMesh.cxx.i -.PHONY : pyKvlMesh.cxx.i - -pyKvlMesh.s: pyKvlMesh.cxx.s -.PHONY : pyKvlMesh.s - -# target to generate assembly for a file -pyKvlMesh.cxx.s: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlMesh.cxx.s -.PHONY : pyKvlMesh.cxx.s - -pyKvlOptimizer.o: pyKvlOptimizer.cxx.o -.PHONY : pyKvlOptimizer.o - -# target to build an object file -pyKvlOptimizer.cxx.o: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlOptimizer.cxx.o -.PHONY : pyKvlOptimizer.cxx.o - -pyKvlOptimizer.i: pyKvlOptimizer.cxx.i -.PHONY : pyKvlOptimizer.i - -# target to preprocess a source file -pyKvlOptimizer.cxx.i: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlOptimizer.cxx.i -.PHONY : pyKvlOptimizer.cxx.i - -pyKvlOptimizer.s: pyKvlOptimizer.cxx.s -.PHONY : pyKvlOptimizer.s - -# target to generate assembly for a file -pyKvlOptimizer.cxx.s: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlOptimizer.cxx.s -.PHONY : pyKvlOptimizer.cxx.s - -pyKvlTransform.o: pyKvlTransform.cxx.o -.PHONY : pyKvlTransform.o - -# target to build an object file -pyKvlTransform.cxx.o: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlTransform.cxx.o -.PHONY : pyKvlTransform.cxx.o - -pyKvlTransform.i: pyKvlTransform.cxx.i -.PHONY : pyKvlTransform.i - -# target to preprocess a source file -pyKvlTransform.cxx.i: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlTransform.cxx.i -.PHONY : pyKvlTransform.cxx.i - -pyKvlTransform.s: pyKvlTransform.cxx.s -.PHONY : pyKvlTransform.s - -# target to generate assembly for a file -pyKvlTransform.cxx.s: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(MAKE) $(MAKESILENT) -f samseg/cxx/CMakeFiles/gemsbindings.dir/build.make samseg/cxx/CMakeFiles/gemsbindings.dir/pyKvlTransform.cxx.s -.PHONY : pyKvlTransform.cxx.s - -# Help Target -help: - @echo "The following are some of the valid targets for this Makefile:" - @echo "... all (the default if no target is provided)" - @echo "... clean" - @echo "... depend" - @echo "... edit_cache" - @echo "... rebuild_cache" - @echo "... gemsbindings" - @echo "... module.o" - @echo "... module.i" - @echo "... module.s" - @echo "... pyKvlCalculator.o" - @echo "... pyKvlCalculator.i" - @echo "... pyKvlCalculator.s" - @echo "... pyKvlImage.o" - @echo "... pyKvlImage.i" - @echo "... pyKvlImage.s" - @echo "... pyKvlMesh.o" - @echo "... pyKvlMesh.i" - @echo "... pyKvlMesh.s" - @echo "... pyKvlOptimizer.o" - @echo "... pyKvlOptimizer.i" - @echo "... pyKvlOptimizer.s" - @echo "... pyKvlTransform.o" - @echo "... pyKvlTransform.i" - @echo "... pyKvlTransform.s" -.PHONY : help - - - -#============================================================================= -# Special targets to cleanup operation of make. - -# Special rule to run CMake to check the build system integrity. -# No rule that depends on this can have commands that come from listfiles -# because they might be regenerated. -cmake_check_build_system: - cd /homes/9/op035/rauma_op035/software/samseg_python && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 -.PHONY : cmake_check_build_system - diff --git a/samseg/cxx/orig_CMakeLists.txt b/samseg/cxx/orig_CMakeLists.txt deleted file mode 100644 index caf0caf..0000000 --- a/samseg/cxx/orig_CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ -include_directories(${CMAKE_SOURCE_DIR}/gems ${CMAKE_CURRENT_SOURCE_DIR}) - -set(CMAKE_CXX_FLAGS "-fPIC -fpermissive -msse2 -mfpmath=sse") - -# temporary fix so that -g doesn't produce linker errors when binding cxx/python code -set(CMAKE_CXX_FLAGS_DEBUG "") -set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "") - -add_compile_options(-Wno-inconsistent-missing-override -Wno-self-assign-field) - -pybind11_add_module(gemsbindings - module.cxx - pyKvlCalculator.cxx - pyKvlImage.cxx - pyKvlMesh.cxx - pyKvlOptimizer.cxx - pyKvlTransform.cxx -) - -# link utilities -target_link_libraries(gemsbindings PRIVATE kvlGEMSCommon) - -# make sure the bindings library gets built into the repository even in out-of-source builds -set_target_properties(gemsbindings PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/python/gems) diff --git a/samseg/gems/_cxx/CMakeLists.txt b/samseg/gems/_cxx/CMakeLists.txt new file mode 100644 index 0000000..e2222c3 --- /dev/null +++ b/samseg/gems/_cxx/CMakeLists.txt @@ -0,0 +1,33 @@ +set(PYBIND11_FINDPYTHON ON) + +FetchContent_Declare(pybind11 + GIT_REPOSITORY https://github.com/pybind/pybind11.git + GIT_TAG v2.13.6 + GIT_SHALLOW TRUE + FIND_PACKAGE_ARGS QUIET +) +FetchContent_MakeAvailable(pybind11) + +pybind11_add_module(gemsbindings + module.cxx + pyKvlCalculator.cxx + pyKvlImage.cxx + pyKvlMesh.cxx + pyKvlOptimizer.cxx + pyKvlTransform.cxx + pyKvlRigidRegistration.cxx + pyKvlAffineRegistration.cxx +) + +target_include_directories(gemsbindings PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries(gemsbindings PRIVATE samseg_warnings samseg_linkopt kvlGEMSCommon) + +# pybind11 debug builds produce objects too large for the linker with -g +if(NOT MSVC) + target_compile_options(gemsbindings PRIVATE + $<$:-g0> + $<$:-g0> + ) +endif() + +install(TARGETS gemsbindings LIBRARY DESTINATION samseg/gems) diff --git a/samseg/cxx/module.cxx b/samseg/gems/_cxx/module.cxx similarity index 100% rename from samseg/cxx/module.cxx rename to samseg/gems/_cxx/module.cxx diff --git a/samseg/cxx/pyKvlAffineRegistration.cxx b/samseg/gems/_cxx/pyKvlAffineRegistration.cxx similarity index 100% rename from samseg/cxx/pyKvlAffineRegistration.cxx rename to samseg/gems/_cxx/pyKvlAffineRegistration.cxx diff --git a/samseg/cxx/pyKvlAffineRegistration.h b/samseg/gems/_cxx/pyKvlAffineRegistration.h similarity index 100% rename from samseg/cxx/pyKvlAffineRegistration.h rename to samseg/gems/_cxx/pyKvlAffineRegistration.h diff --git a/samseg/cxx/pyKvlCalculator.cxx b/samseg/gems/_cxx/pyKvlCalculator.cxx similarity index 100% rename from samseg/cxx/pyKvlCalculator.cxx rename to samseg/gems/_cxx/pyKvlCalculator.cxx diff --git a/samseg/cxx/pyKvlCalculator.h b/samseg/gems/_cxx/pyKvlCalculator.h similarity index 100% rename from samseg/cxx/pyKvlCalculator.h rename to samseg/gems/_cxx/pyKvlCalculator.h diff --git a/samseg/cxx/pyKvlImage.cxx b/samseg/gems/_cxx/pyKvlImage.cxx similarity index 98% rename from samseg/cxx/pyKvlImage.cxx rename to samseg/gems/_cxx/pyKvlImage.cxx index 3f92313..dbb631f 100644 --- a/samseg/cxx/pyKvlImage.cxx +++ b/samseg/gems/_cxx/pyKvlImage.cxx @@ -31,8 +31,6 @@ py::array_t KvlImage::image_to_numpy(ImagePointer image) { } ImagePointer KvlImage::numpy_to_image(const py::array_t &buffer) { - typedef typename ImageType::PixelType PixelType; - // Determine the size of the image to be created typedef typename ImageType::SizeType SizeType; SizeType imageSize; @@ -130,7 +128,6 @@ void KvlImage::Write(std::string fileName, KvlTransform &transform) { ImagePointer image = m_image; if ( true ) { - typedef kvl::CroppedImageReader::TransformType TransformType; // In order not to modify the original image, we create a new one. The proper way of doing this // would be to only copy the header information and of course not the pixel intensities, but I'm // too lazy now to figure out how to do it in ITK diff --git a/samseg/cxx/pyKvlImage.h b/samseg/gems/_cxx/pyKvlImage.h similarity index 100% rename from samseg/cxx/pyKvlImage.h rename to samseg/gems/_cxx/pyKvlImage.h diff --git a/samseg/cxx/pyKvlImageRegisterer.cxx b/samseg/gems/_cxx/pyKvlImageRegisterer.cxx similarity index 100% rename from samseg/cxx/pyKvlImageRegisterer.cxx rename to samseg/gems/_cxx/pyKvlImageRegisterer.cxx diff --git a/samseg/cxx/pyKvlImageRegisterer.h b/samseg/gems/_cxx/pyKvlImageRegisterer.h similarity index 100% rename from samseg/cxx/pyKvlImageRegisterer.h rename to samseg/gems/_cxx/pyKvlImageRegisterer.h diff --git a/samseg/cxx/pyKvlMesh.cxx b/samseg/gems/_cxx/pyKvlMesh.cxx similarity index 100% rename from samseg/cxx/pyKvlMesh.cxx rename to samseg/gems/_cxx/pyKvlMesh.cxx diff --git a/samseg/cxx/pyKvlMesh.h b/samseg/gems/_cxx/pyKvlMesh.h similarity index 100% rename from samseg/cxx/pyKvlMesh.h rename to samseg/gems/_cxx/pyKvlMesh.h diff --git a/samseg/cxx/pyKvlNumpy.h b/samseg/gems/_cxx/pyKvlNumpy.h similarity index 100% rename from samseg/cxx/pyKvlNumpy.h rename to samseg/gems/_cxx/pyKvlNumpy.h diff --git a/samseg/cxx/pyKvlOptimizer.cxx b/samseg/gems/_cxx/pyKvlOptimizer.cxx similarity index 100% rename from samseg/cxx/pyKvlOptimizer.cxx rename to samseg/gems/_cxx/pyKvlOptimizer.cxx diff --git a/samseg/cxx/pyKvlOptimizer.h b/samseg/gems/_cxx/pyKvlOptimizer.h similarity index 100% rename from samseg/cxx/pyKvlOptimizer.h rename to samseg/gems/_cxx/pyKvlOptimizer.h diff --git a/samseg/cxx/pyKvlRigidRegistration.cxx b/samseg/gems/_cxx/pyKvlRigidRegistration.cxx similarity index 100% rename from samseg/cxx/pyKvlRigidRegistration.cxx rename to samseg/gems/_cxx/pyKvlRigidRegistration.cxx diff --git a/samseg/cxx/pyKvlRigidRegistration.h b/samseg/gems/_cxx/pyKvlRigidRegistration.h similarity index 98% rename from samseg/cxx/pyKvlRigidRegistration.h rename to samseg/gems/_cxx/pyKvlRigidRegistration.h index c233179..2e29712 100644 --- a/samseg/cxx/pyKvlRigidRegistration.h +++ b/samseg/gems/_cxx/pyKvlRigidRegistration.h @@ -1,4 +1,4 @@ -#ifndef GEMS_PYKVRIGIDREGISTRATION_H +#ifndef GEMS_PYKVLRIGIDREGISTRATION_H #define GEMS_PYKVLRIGIDREGISTRATION_H #include diff --git a/samseg/cxx/pyKvlTransform.cxx b/samseg/gems/_cxx/pyKvlTransform.cxx similarity index 100% rename from samseg/cxx/pyKvlTransform.cxx rename to samseg/gems/_cxx/pyKvlTransform.cxx diff --git a/samseg/cxx/pyKvlTransform.h b/samseg/gems/_cxx/pyKvlTransform.h similarity index 100% rename from samseg/cxx/pyKvlTransform.h rename to samseg/gems/_cxx/pyKvlTransform.h diff --git a/samseg/tests/__init__.py b/samseg/tests/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 8113138..0000000 --- a/setup.cfg +++ /dev/null @@ -1,55 +0,0 @@ -[metadata] -name = samseg -author = Koen Van Leemput, Oula Puonti, Juan Eugenio Iglesias, Stefano Cerri -maintainer = Koen Van Leemput, Oula Puonti, Juan Eugenio Iglesias, Stefano Cerri -license = MIT -classifiers= - Programming Language :: Python :: 3 - License :: OSI Approved :: MIT License - Operating System :: OS Independent -description = Sequence-Adaptive Multimodal SEGmenation (SAMSEG) -long_description = file: README.md -long_description_content_type = text/markdown -url=https://github.com/freesurfer/samseg - - -[options] -zip_safe = False -include_package_data = True -python_requires >= 3.6 -packages = find: -install_requires = - surfa@git+https://github.com/freesurfer/surfa.git@master - scikit-learn - numpy - numba - - -[options.package_data] -* = ./samseg/atlas/* - -[options.entry_points] -console_scripts= - run_samseg = samseg.cli.run_samseg:main - computeTissueConcentrations = samseg.cli.computeTissueConcentrations:main - prepareAtlasDirectory = samseg.cli.prepareAtlasDirectory:main - run_samseg_long = samseg.cli.run_samseg_long:main - segment_subregions = samseg.cli.segment_subregions:main - sbtiv = samseg.cli.sbtiv:main - gems_compute_atlas_probs = samseg.cli.gems_compute_atlas_probs:main - merge_add_mesh_alphas = samseg.cli.merge_add_mesh_alphas:main - - - -[options.extras_require] -test = - pytest - tensorflow - -[versioneer] -VCS = git -style = pep440 -versionfile_source = samseg/_version.py -versionfile_build = samseg/_version.py -tag_prefix = -parentdir_prefix = diff --git a/setup.py b/setup.py deleted file mode 100644 index 92a6a63..0000000 --- a/setup.py +++ /dev/null @@ -1,74 +0,0 @@ -from setuptools import setup, Extension -from setuptools.command.build_ext import build_ext -import versioneer -import os -import sys -import shutil -import glob -import subprocess -import tempfile - -# RUN with ITK_DIR="PATH_TO_ITK" python setup.py - -# Replace build-ext to run CMake in order to build the bindings -class build_ext_(build_ext): - def run(self): - package_root = os.path.abspath(os.path.dirname(__file__)) - # Run CMAKE - with tempfile.TemporaryDirectory() as tmpdir: - cmake_call = [ - 'cmake', - '-DCMAKE_BUILD_TYPE=Release', - f'-DPYTHON_EXECUTABLE={sys.executable}', - f'-B{tmpdir}', - '-H.' - ] - # Pass environment variables to CMake - for k in ['ITK_DIR', 'ZLIB_INCLUDE_DIR', 'ZLIB_LIBRARY', 'pybind11_DIR', 'CMAKE_C_COMPILER', 'CMAKE_CXX_COMPILER', 'APPLE_ARM64', 'CMAKE_VERBOSE_MAKEFILE', 'CMAKE_RULE_MESSAGES']: - try: - path = os.path.abspath(os.environ[k].replace('"', '')) - except KeyError: - pass - else: - cmake_call += [f'-D{k}={path}'] - print(' '.join(cmake_call)) - subprocess.run(cmake_call, check=True) - # Run Make - if sys.platform == 'win32': - subprocess.run([ - 'cmake', '--build', tmpdir, - '--config', 'Release'], - check=True - ) - compiled_lib = glob.glob(os.path.join( - package_root, 'samseg', 'gems', 'Release', 'gemsbindings.*.pyd' - )) - else: - subprocess.run(['make', '-C', tmpdir], check=True) - compiled_lib = glob.glob(os.path.join( - package_root, 'samseg', 'gems', 'gemsbindings.cpython-*.so' - )) - # Move compiled libraries to build folder and charm_gems folder - if len(compiled_lib) == 0: - raise OSError( - 'Something went wrong during compilation ' - 'did not find any compiled libraries' - ) - if len(compiled_lib) > 1: - raise OSError( - 'Found many compiled libraries. Please clean it up and try again' - ) - - if self.inplace is False: - shutil.copy(compiled_lib[0], os.path.join(self.build_lib,'samseg', 'gems')) - - -setup( - version=versioneer.get_version(), - ext_modules=[ - Extension( - 'samseg.gems.gemsbindings', ['dummy'], - depends=glob.glob('gems*/*.cxx') + glob.glob('gems*/*.h') - )], - cmdclass={'build_ext': build_ext_,}, -) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..c19f8d1 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,93 @@ +import pytest +import os +import numpy as np +from pathlib import Path + +from samseg import SAMSEGDIR + + +@pytest.fixture(scope="session") +def test_data_dir(): + """Returns the absolute path to the 'resources' directory.""" + return Path(__file__).parent / "resources" + + +@pytest.fixture(scope="module") +def testernie_nii(test_data_dir): + fn = os.path.join(test_data_dir, "ernie_T1_ds5.nii.gz") + return fn + + +@pytest.fixture(scope="module") +def testmni_nii(test_data_dir): + fn = os.path.join(test_data_dir, "MNI_test_ds5.nii.gz") + return fn + + +@pytest.fixture(scope="module") +def testtemplate_nii(): + fn = os.path.join( + SAMSEGDIR, + "atlas", + "20Subjects_smoothing2_down2_smoothingForAffine2", + "template.nii.gz", + ) + return fn + + +@pytest.fixture(scope="module") +def testaffinemesh_msh(): + fn = os.path.join( + SAMSEGDIR, + "atlas", + "20Subjects_smoothing2_down2_smoothingForAffine2", + "atlasForAffineRegistration.txt.gz", + ) + return fn + + +@pytest.fixture(scope="module") +def testaffine_mat(test_data_dir): + fn = os.path.join(test_data_dir, "template_transforms.mat") + return fn + + +@pytest.fixture(scope="module") +def testcubenoise_nii(test_data_dir): + fn = os.path.join(test_data_dir, "cube_noise.nii.gz") + return fn + + +@pytest.fixture(scope="module") +def testcubenoise_2_nii(test_data_dir): + fn = os.path.join(test_data_dir, "cube_noise_2.nii.gz") + return fn + + +@pytest.fixture(scope="module") +def testcube_nii(test_data_dir): + fn = os.path.join(test_data_dir, "cube.nii.gz") + return fn + + +@pytest.fixture(scope="module") +def testcubeatlas_path(test_data_dir): + fn = os.path.join(test_data_dir, "cube_atlas") + return fn + + +@pytest.fixture +def tmppath(tmpdir): + return str(tmpdir) + + +@pytest.fixture(scope="session") +def calc_dice(): + """ + Utility function to calculate the magnitude difference in log space. + """ + + def _calc_dice(vol1, vol2): + return np.sum(vol2[vol1]) * 2.0 / (np.sum(vol1) + np.sum(vol2)) + + return _calc_dice diff --git a/samseg/_internal_resources/testing_files/MNI_test_ds5.nii.gz b/tests/resources/MNI_test_ds5.nii.gz similarity index 100% rename from samseg/_internal_resources/testing_files/MNI_test_ds5.nii.gz rename to tests/resources/MNI_test_ds5.nii.gz diff --git a/samseg/_internal_resources/testing_files/cube.nii.gz b/tests/resources/cube.nii.gz similarity index 100% rename from samseg/_internal_resources/testing_files/cube.nii.gz rename to tests/resources/cube.nii.gz diff --git a/samseg/_internal_resources/testing_files/cube_atlas/atlas.txt.gz b/tests/resources/cube_atlas/atlas.txt.gz similarity index 100% rename from samseg/_internal_resources/testing_files/cube_atlas/atlas.txt.gz rename to tests/resources/cube_atlas/atlas.txt.gz diff --git a/samseg/_internal_resources/testing_files/cube_atlas/compressionLookupTable.txt b/tests/resources/cube_atlas/compressionLookupTable.txt similarity index 100% rename from samseg/_internal_resources/testing_files/cube_atlas/compressionLookupTable.txt rename to tests/resources/cube_atlas/compressionLookupTable.txt diff --git a/samseg/_internal_resources/testing_files/cube_atlas/modifiedFreeSurferColorLUT.txt b/tests/resources/cube_atlas/modifiedFreeSurferColorLUT.txt similarity index 100% rename from samseg/_internal_resources/testing_files/cube_atlas/modifiedFreeSurferColorLUT.txt rename to tests/resources/cube_atlas/modifiedFreeSurferColorLUT.txt diff --git a/samseg/_internal_resources/testing_files/cube_atlas/sharedGMMParameters.txt b/tests/resources/cube_atlas/sharedGMMParameters.txt similarity index 100% rename from samseg/_internal_resources/testing_files/cube_atlas/sharedGMMParameters.txt rename to tests/resources/cube_atlas/sharedGMMParameters.txt diff --git a/samseg/_internal_resources/testing_files/cube_atlas/template.nii.gz b/tests/resources/cube_atlas/template.nii.gz similarity index 100% rename from samseg/_internal_resources/testing_files/cube_atlas/template.nii.gz rename to tests/resources/cube_atlas/template.nii.gz diff --git a/samseg/_internal_resources/testing_files/cube_noise.nii.gz b/tests/resources/cube_noise.nii.gz similarity index 100% rename from samseg/_internal_resources/testing_files/cube_noise.nii.gz rename to tests/resources/cube_noise.nii.gz diff --git a/samseg/_internal_resources/testing_files/cube_noise_2.nii.gz b/tests/resources/cube_noise_2.nii.gz similarity index 100% rename from samseg/_internal_resources/testing_files/cube_noise_2.nii.gz rename to tests/resources/cube_noise_2.nii.gz diff --git a/samseg/_internal_resources/testing_files/ernie_T1_ds5.nii.gz b/tests/resources/ernie_T1_ds5.nii.gz similarity index 100% rename from samseg/_internal_resources/testing_files/ernie_T1_ds5.nii.gz rename to tests/resources/ernie_T1_ds5.nii.gz diff --git a/samseg/_internal_resources/testing_files/template_transforms.mat b/tests/resources/template_transforms.mat similarity index 100% rename from samseg/_internal_resources/testing_files/template_transforms.mat rename to tests/resources/template_transforms.mat diff --git a/samseg/tests/test_samseg.py b/tests/test_samseg.py similarity index 83% rename from samseg/tests/test_samseg.py rename to tests/test_samseg.py index b5827ee..5eb3114 100644 --- a/samseg/tests/test_samseg.py +++ b/tests/test_samseg.py @@ -1,88 +1,14 @@ import numpy as np -import pytest import surfa as sf import os +from scipy.io import loadmat + import samseg from samseg import SamsegLesion, SamsegLongitudinalLesion -from scipy import ndimage -from scipy.io import loadmat -from .. import SAMSEGDIR -from ..SamsegUtility import coregister -from ..Affine import initializationOptions -from ..Samseg import initVisualizer, Samseg -from ..io import kvlReadSharedGMMParameters - -# This is a hack to test an installed wheel -# Because the test data is not in the wheel -# the tests would fail. If you export the -# SAMSEG_TEST_PATH variable to point to -# the source code directory, the test data -# is picked up from there instead. -try: - SAMSEGDIR = os.environ['SAMSEG_TEST_PATH'] -except KeyError: - print("No environment variable set, using standard path.") - -@pytest.fixture(scope='module') -def testernie_nii(): - fn = os.path.join( - SAMSEGDIR, '_internal_resources', 'testing_files', 'ernie_T1_ds5.nii.gz') - return fn - -@pytest.fixture(scope='module') -def testmni_nii(): - fn = os.path.join( - SAMSEGDIR, '_internal_resources', 'testing_files', 'MNI_test_ds5.nii.gz') - return fn - -@pytest.fixture(scope='module') -def testtemplate_nii(): - fn = os.path.join( - SAMSEGDIR, 'atlas', '20Subjects_smoothing2_down2_smoothingForAffine2', 'template.nii.gz') - return fn - -@pytest.fixture(scope='module') -def testaffinemesh_msh(): - fn = os.path.join( - SAMSEGDIR, 'atlas', '20Subjects_smoothing2_down2_smoothingForAffine2', 'atlasForAffineRegistration.txt.gz') - return fn - -@pytest.fixture(scope='module') -def testaffine_mat(): - fn = os.path.join( - SAMSEGDIR, '_internal_resources', 'testing_files', 'template_transforms.mat') - return fn - -@pytest.fixture(scope='module') -def testcubenoise_nii(): - fn = os.path.join( - SAMSEGDIR, '_internal_resources', 'testing_files', 'cube_noise.nii.gz') - return fn - -@pytest.fixture(scope='module') -def testcubenoise_2_nii(): - fn = os.path.join( - SAMSEGDIR, '_internal_resources', 'testing_files', 'cube_noise_2.nii.gz') - return fn - -@pytest.fixture(scope='module') -def testcube_nii(): - fn = os.path.join( - SAMSEGDIR, '_internal_resources', 'testing_files', 'cube.nii.gz') - return fn - -@pytest.fixture(scope='module') -def testcubeatlas_path(): - fn = os.path.join( - SAMSEGDIR, '_internal_resources', 'testing_files', 'cube_atlas') - return fn - -@pytest.fixture -def tmppath(tmpdir): - return str(tmpdir) - -def _calc_dice(vol1, vol2): - return np.sum(vol2[vol1])*2.0 / (np.sum(vol1) + np.sum(vol2)) +from samseg.SamsegUtility import coregister +from samseg.Affine import initializationOptions +from samseg.Samseg import initVisualizer +from samseg.io import kvlReadSharedGMMParameters def test_mni_affine(tmppath, testmni_nii): @@ -202,7 +128,7 @@ def test_coregistration(tmppath, testmni_nii): assert (np.corrcoef(reg_scan.data.flatten(), trans_mni.data.flatten()))[0,1] > 0.99 -def test_segmentation(tmppath, testcube_nii, testcubenoise_nii, testcubeatlas_path): +def test_segmentation(tmppath, testcube_nii, testcubenoise_nii, testcubeatlas_path, calc_dice): os.mkdir(os.path.join(tmppath, "segmentation")) seg_dir = os.path.join(tmppath, "segmentation") @@ -257,12 +183,12 @@ def test_segmentation(tmppath, testcube_nii, testcubenoise_nii, testcubeatlas_pa seg = os.path.join(str(seg_dir), 'seg.mgz') orig_cube = sf.load_volume(testcube_nii) est_cube = sf.load_volume(seg) - dice = _calc_dice(orig_cube.data==1, est_cube.data==1) + dice = calc_dice(orig_cube.data==1, est_cube.data==1) print("Dice score: " + str(dice)) assert dice > 0.95 -def test_segmentation_lesion(tmppath, testcube_nii, testcubenoise_nii, testcubeatlas_path): +def test_segmentation_lesion(tmppath, testcube_nii, testcubenoise_nii, testcubeatlas_path, calc_dice): os.mkdir(os.path.join(tmppath, "segmentation")) seg_dir = os.path.join(tmppath, "segmentation") @@ -325,12 +251,12 @@ def test_segmentation_lesion(tmppath, testcube_nii, testcubenoise_nii, testcubea seg = os.path.join(str(seg_dir), 'seg.mgz') orig_cube = sf.load_volume(testcube_nii) est_cube = sf.load_volume(seg) - dice = _calc_dice(orig_cube.data==1, est_cube.data==1) + dice = calc_dice(orig_cube.data==1, est_cube.data==1) print("Dice score: " + str(dice)) assert dice > 0.95 -def test_long_segmentation(tmppath, testcube_nii, testcubenoise_nii, testcubenoise_2_nii, testcubeatlas_path): +def test_long_segmentation(tmppath, testcube_nii, testcubenoise_nii, testcubenoise_2_nii, testcubeatlas_path, calc_dice): os.mkdir(os.path.join(tmppath, "segmentation")) seg_dir = os.path.join(tmppath, "segmentation") @@ -390,16 +316,16 @@ def test_long_segmentation(tmppath, testcube_nii, testcubenoise_nii, testcubenoi est_cube_tp0 = sf.load_volume(seg_tp0) est_cube_tp1 = sf.load_volume(seg_tp1) - dice = _calc_dice(orig_cube.data==1, est_cube_tp0.data==1) + dice = calc_dice(orig_cube.data==1, est_cube_tp0.data==1) print("Dice score tp 0: " + str(dice)) assert dice > 0.95 - dice = _calc_dice(orig_cube.data==1, est_cube_tp1.data==1) + dice = calc_dice(orig_cube.data==1, est_cube_tp1.data==1) print("Dice score tp 1: " + str(dice)) assert dice > 0.95 -def test_long_segmentation_lesion(tmppath, testcube_nii, testcubenoise_nii, testcubenoise_2_nii, testcubeatlas_path): +def test_long_segmentation_lesion(tmppath, testcube_nii, testcubenoise_nii, testcubenoise_2_nii, testcubeatlas_path, calc_dice): os.mkdir(os.path.join(tmppath, "segmentation")) seg_dir = os.path.join(tmppath, "segmentation") @@ -467,11 +393,10 @@ def test_long_segmentation_lesion(tmppath, testcube_nii, testcubenoise_nii, test est_cube_tp0 = sf.load_volume(seg_tp0) est_cube_tp1 = sf.load_volume(seg_tp1) - dice = _calc_dice(orig_cube.data==1, est_cube_tp0.data==1) + dice = calc_dice(orig_cube.data==1, est_cube_tp0.data==1) print("Dice score tp 0: " + str(dice)) assert dice > 0.95 - dice = _calc_dice(orig_cube.data==1, est_cube_tp1.data==1) + dice = calc_dice(orig_cube.data==1, est_cube_tp1.data==1) print("Dice score tp 1: " + str(dice)) assert dice > 0.95 - diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 18e34c2..0000000 --- a/versioneer.py +++ /dev/null @@ -1,2205 +0,0 @@ - -# Version: 0.28 - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/python-versioneer/python-versioneer -* Brian Warner -* License: Public Domain (Unlicense) -* Compatible with: Python 3.7, 3.8, 3.9, 3.10 and pypy3 -* [![Latest Version][pypi-image]][pypi-url] -* [![Build Status][travis-image]][travis-url] - -This is a tool for managing a recorded version number in setuptools-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -Versioneer provides two installation modes. The "classic" vendored mode installs -a copy of versioneer into your repository. The experimental build-time dependency mode -is intended to allow you to skip this step and simplify the process of upgrading. - -### Vendored mode - -* `pip install versioneer` to somewhere in your $PATH - * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is - available, so you can also use `conda install -c conda-forge versioneer` -* add a `[tool.versioneer]` section to your `pyproject.toml` or a - `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) - * Note that you will need to add `tomli; python_version < "3.11"` to your - build-time dependencies if you use `pyproject.toml` -* run `versioneer install --vendor` in your source tree, commit the results -* verify version information with `python setup.py version` - -### Build-time dependency mode - -* `pip install versioneer` to somewhere in your $PATH - * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is - available, so you can also use `conda install -c conda-forge versioneer` -* add a `[tool.versioneer]` section to your `pyproject.toml` or a - `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) -* add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`) - to the `requires` key of the `build-system` table in `pyproject.toml`: - ```toml - [build-system] - requires = ["setuptools", "versioneer[toml]"] - build-backend = "setuptools.build_meta" - ``` -* run `versioneer install --no-vendor` in your source tree, commit the results -* verify version information with `python setup.py version` - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes). - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the - commit date in ISO 8601 format. This will be None if the date is not - available. - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See [details.md](details.md) in the Versioneer -source tree for descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -Some situations are known to cause problems for Versioneer. This details the -most significant ones. More can be found on Github -[issues page](https://github.com/python-versioneer/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI - distributions (and upload multiple independently-installable tarballs). -* Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other languages) in subdirectories. - -Versioneer will look for `.git` in parent directories, and most operations -should get the right version string. However `pip` and `setuptools` have bugs -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in -some later version. - -[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking -this issue. The discussion in -[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the -issue from the Versioneer side in more detail. -[pip PR#3176](https://github.com/pypa/pip/pull/3176) and -[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into -a different virtualenv), so this can be surprising. - -[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg` and `pyproject.toml`, if necessary, - to include any new configuration settings indicated by the release notes. - See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install --[no-]vendor` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - -## Similar projects - -* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time - dependency -* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of - versioneer -* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools - plugin - -## License - -To make Versioneer easier to embed, all its code is dedicated to the public -domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the "Unlicense", as described in -https://unlicense.org/. - -[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg -[pypi-url]: https://pypi.python.org/pypi/versioneer/ -[travis-image]: -https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg -[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer - -""" -# pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring -# pylint:disable=missing-class-docstring,too-many-branches,too-many-statements -# pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error -# pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with -# pylint:disable=attribute-defined-outside-init,too-many-arguments - -import configparser -import errno -import json -import os -import re -import subprocess -import sys -from pathlib import Path -from typing import Callable, Dict -import functools - -have_tomllib = True -if sys.version_info >= (3, 11): - import tomllib -else: - try: - import tomli as tomllib - except ImportError: - have_tomllib = False - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - my_path = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(my_path)[0]) - vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(my_path), versioneer_py)) - except NameError: - pass - return root - - -def get_config_from_root(root): - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise OSError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - root = Path(root) - pyproject_toml = root / "pyproject.toml" - setup_cfg = root / "setup.cfg" - section = None - if pyproject_toml.exists() and have_tomllib: - try: - with open(pyproject_toml, 'rb') as fobj: - pp = tomllib.load(fobj) - section = pp['tool']['versioneer'] - except (tomllib.TOMLDecodeError, KeyError): - pass - if not section: - parser = configparser.ConfigParser() - with open(setup_cfg) as cfg_file: - parser.read_file(cfg_file) - parser.get("versioneer", "VCS") # raise error if missing - - section = parser["versioneer"] - - cfg = VersioneerConfig() - cfg.VCS = section['VCS'] - cfg.style = section.get("style", "") - cfg.versionfile_source = section.get("versionfile_source") - cfg.versionfile_build = section.get("versionfile_build") - cfg.tag_prefix = section.get("tag_prefix") - if cfg.tag_prefix in ("''", '""', None): - cfg.tag_prefix = "" - cfg.parentdir_prefix = section.get("parentdir_prefix") - cfg.verbose = section.get("verbose") - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - HANDLERS.setdefault(vcs, {})[method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, process.returncode - return stdout, process.returncode - - -LONG_VERSION_PY['git'] = r''' -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. -# Generated by versioneer-0.28 -# https://github.com/python-versioneer/python-versioneer - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys -from typing import Callable, Dict -import functools - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - print("stdout was %%s" %% stdout) - return None, process.returncode - return stdout, process.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs - tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver): - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces): - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%%d" %% (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for _ in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def do_vcs_install(versionfile_source, ipy): - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [versionfile_source] - if ipy: - files.append(ipy) - if "VERSIONEER_PEP518" not in globals(): - try: - my_path = __file__ - if my_path.endswith((".pyc", ".pyo")): - my_path = os.path.splitext(my_path)[0] + ".py" - versioneer_file = os.path.relpath(my_path) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - with open(".gitattributes", "r") as fobj: - for line in fobj: - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - break - except OSError: - pass - if not present: - with open(".gitattributes", "a+") as fobj: - fobj.write(f"{versionfile_source} export-subst\n") - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.28) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename): - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except OSError: - raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename, versions): - """Write the given version number to the given _version.py file.""" - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver): - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces): - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%d" % (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose=False): - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version", - "date": None} - - -def get_version(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(cmdclass=None): - """Get the custom setuptools subclasses used by Versioneer. - - If the package uses a different cmdclass (e.g. one from numpy), it - should be provide as an argument. - """ - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/python-versioneer/python-versioneer/issues/52 - - cmds = {} if cmdclass is None else cmdclass.copy() - - # we add "version" to setuptools - from setuptools import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # pip install -e . and setuptool/editable_wheel will invoke build_py - # but the build_py command is not expected to copy any files. - - # we override different "build_py" commands for both environments - if 'build_py' in cmds: - _build_py = cmds['build_py'] - else: - from setuptools.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - if getattr(self, "editable_mode", False): - # During editable installs `.py` and data files are - # not copied to build_lib - return - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if 'build_ext' in cmds: - _build_ext = cmds['build_ext'] - else: - from setuptools.command.build_ext import build_ext as _build_ext - - class cmd_build_ext(_build_ext): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_ext.run(self) - if self.inplace: - # build_ext --inplace will only build extensions in - # build/lib<..> dir with no _version.py to write to. - # As in place builds will already have a _version.py - # in the module dir, we do not need to write one. - return - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if not cfg.versionfile_build: - return - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - if not os.path.exists(target_versionfile): - print(f"Warning: {target_versionfile} does not exist, skipping " - "version update. This can happen if you are running build_ext " - "without first running build_py.") - return - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_ext"] = cmd_build_ext - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if 'py2exe' in sys.modules: # py2exe enabled? - try: - from py2exe.setuptools_buildexe import py2exe as _py2exe - except ImportError: - from py2exe.distutils_buildexe import py2exe as _py2exe - - class cmd_py2exe(_py2exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["py2exe"] = cmd_py2exe - - # sdist farms its file list building out to egg_info - if 'egg_info' in cmds: - _egg_info = cmds['egg_info'] - else: - from setuptools.command.egg_info import egg_info as _egg_info - - class cmd_egg_info(_egg_info): - def find_sources(self): - # egg_info.find_sources builds the manifest list and writes it - # in one shot - super().find_sources() - - # Modify the filelist and normalize it - root = get_root() - cfg = get_config_from_root(root) - self.filelist.append('versioneer.py') - if cfg.versionfile_source: - # There are rare cases where versionfile_source might not be - # included by default, so we must be explicit - self.filelist.append(cfg.versionfile_source) - self.filelist.sort() - self.filelist.remove_duplicates() - - # The write method is hidden in the manifest_maker instance that - # generated the filelist and was thrown away - # We will instead replicate their final normalization (to unicode, - # and POSIX-style paths) - from setuptools import unicode_utils - normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/') - for f in self.filelist.files] - - manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') - with open(manifest_filename, 'w') as fobj: - fobj.write('\n'.join(normalized)) - - cmds['egg_info'] = cmd_egg_info - - # we override different "sdist" commands for both environments - if 'sdist' in cmds: - _sdist = cmds['sdist'] - else: - from setuptools.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -OLD_SNIPPET = """ -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - -INIT_PY_SNIPPET = """ -from . import {0} -__version__ = {0}.get_versions()['version'] -""" - - -def do_setup(): - """Do main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except (OSError, configparser.NoSectionError, - configparser.NoOptionError) as e: - if isinstance(e, (OSError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except OSError: - old = "" - module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] - snippet = INIT_PY_SNIPPET.format(module) - if OLD_SNIPPET in old: - print(" replacing boilerplate in %s" % ipy) - with open(ipy, "w") as f: - f.write(old.replace(OLD_SNIPPET, snippet)) - elif snippet not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(snippet) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -def setup_command(): - """Set up Versioneer and exit with appropriate error code.""" - errors = do_setup() - errors += scan_setup_py() - sys.exit(1 if errors else 0) - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - setup_command()