From bf18b0e73654c2e581c16c258f44fd90086e6cb2 Mon Sep 17 00:00:00 2001 From: Yulin-W <65204338+Yulin-W@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:56:21 +1100 Subject: [PATCH 1/2] build: automate wheel building --- .github/workflows/release.yml | 33 ----- .github/workflows/wheels.yml | 243 +++++++++++++++++++++++++++++++++ .gitignore | 3 + CMakeLists.txt | 124 ++++++++++++----- MANIFEST.in | 26 ++++ pyproject.toml | 29 +++- setup.py | 140 +++++++++++++++---- tests/compat.py | 32 ----- tests/test_data.py | 2 +- tests/test_model.py | 2 +- tests/test_priors.py | 2 +- tests/test_reference_parity.py | 2 +- wavefactor/__init__.py | 5 +- 13 files changed, 506 insertions(+), 137 deletions(-) delete mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/wheels.yml create mode 100644 MANIFEST.in delete mode 100644 tests/compat.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 7a6979a..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: Release - -on: - push: - branches: - - main - paths: - - 'VERSION' - -permissions: - contents: write - -jobs: - release: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Create GitHub Release - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - VERSION=$(cat VERSION | tr -d '[:space:]') - TAG="v$VERSION" - if git rev-parse "$TAG" >/dev/null 2>&1; then - echo "Tag $TAG already exists. Skipping release." - else - gh release create "$TAG" --title "$TAG" --generate-notes - fi - shell: bash diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml new file mode 100644 index 0000000..f6add8d --- /dev/null +++ b/.github/workflows/wheels.yml @@ -0,0 +1,243 @@ +name: Test, Build Wheels & Publish to PyPI + +# Pull requests and manual dispatch run the full test + build pipeline but never publish. +# Publishing only happens on a push to main that changes VERSION (or a manual dispatch from +# main with publish=true), and only after ALL test and build jobs below have succeeded. +on: + push: + branches: + - main + paths: + - "VERSION" + pull_request: + paths: + - "src/**" + - "test/**" + - "tests/**" + - "wavefactor/**" + - "lib/**" + - "CMakeLists.txt" + - "setup.py" + - "pyproject.toml" + - "MANIFEST.in" + - "VERSION" + - ".github/workflows/wheels.yml" + workflow_dispatch: + inputs: + publish: + description: "Publish built wheels & sdist to PyPI and GitHub Release (main branch only)" + required: false + default: false + type: boolean + +permissions: + contents: read + +concurrency: + group: wheels-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + cpp_tests: + name: C++ GoogleTests on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-15] + steps: + - uses: actions/checkout@v4 + + - name: Configure (C++ tests only; Python module is built and tested by the wheel jobs) + run: cmake -S . -B build-cpp -DCMAKE_BUILD_TYPE=Release -DBUILD_PYTHON_MODULE=OFF -DBUILD_CPP_TESTS=ON + shell: bash + + - name: Build WaveFactorTests + run: cmake --build build-cpp --config Release --target WaveFactorTests --parallel + shell: bash + + - name: Run GoogleTests via CTest + run: ctest --test-dir build-cpp -C Release --output-on-failure --no-tests=error + shell: bash + + build_wheels: + name: Build & test wheels on ${{ matrix.os }} (${{ matrix.cibw_archs }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + # Linux x86_64 (manylinux_2_28) + - os: ubuntu-latest + cibw_archs: "x86_64" + # Windows AMD64 (MSVC) + - os: windows-latest + cibw_archs: "AMD64" + # macOS Apple Silicon (arm64) + - os: macos-15 + cibw_archs: "arm64" + # macOS Intel (x86_64) + - os: macos-15-intel + cibw_archs: "x86_64" + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # Python versions are selected in pyproject.toml ([tool.cibuildwheel]). + # cibuildwheel runs the Python test suite against every built wheel and fails the job + # if any test fails. + - name: Build wheels via cibuildwheel + uses: pypa/cibuildwheel@v3.4.1 + env: + CIBW_ARCHS: ${{ matrix.cibw_archs }} + + - uses: actions/upload-artifact@v4 + with: + name: cibw-wheels-${{ matrix.os }}-${{ matrix.cibw_archs }} + path: ./wheelhouse/*.whl + if-no-files-found: error + + build_sdist: + name: Build source distribution (sdist) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Build sdist + run: pipx run build --sdist + + - uses: actions/upload-artifact@v4 + with: + name: cibw-sdist + path: dist/*.tar.gz + if-no-files-found: error + + test_sdist: + name: Install & test from sdist + needs: [build_sdist] + runs-on: ubuntu-latest + steps: + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - uses: actions/download-artifact@v4 + with: + name: cibw-sdist + path: dist + + # Builds the extension from the sdist alone (no git checkout), which verifies + # that MANIFEST.in ships everything required to compile. + - name: Install from sdist + run: python -m pip install pytest dist/*.tar.gz + shell: bash + + - name: Run Python tests from the unpacked sdist against the installed package + run: | + set -euo pipefail + mkdir sdist_src + tar -xzf dist/*.tar.gz -C sdist_src --strip-components=1 + pytest sdist_src/tests + shell: bash + + publish: + name: Publish to PyPI & GitHub Release + # Every test and build job must succeed before anything is published anywhere. + needs: [cpp_tests, build_wheels, build_sdist, test_sdist] + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + if: >- + (github.event_name == 'push' && github.ref == 'refs/heads/main') || + (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.publish == true || github.event.inputs.publish == 'true')) + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Download wheel and sdist artifacts + uses: actions/download-artifact@v4 + with: + pattern: cibw-* + path: dist + merge-multiple: true + + - name: Validate version and distribution artifacts + run: | + set -euo pipefail + VERSION=$(tr -d '[:space:]' < VERSION) + if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+((a|b|rc)[0-9]+)?(\.post[0-9]+)?(\.dev[0-9]+)?$ ]]; then + echo "Invalid VERSION string (expected PEP 440 X.Y.Z[aN|bN|rcN][.postN][.devN]): '$VERSION'" >&2 + exit 1 + fi + shopt -s nullglob + wheels=(dist/*.whl) + sdists=(dist/*.tar.gz) + echo "Downloaded ${#wheels[@]} wheel(s) and ${#sdists[@]} sdist(s):" + ls -lh dist/ + # 4 platforms x 4 CPython versions (3.10 - 3.13) = 16 wheels + if [[ ${#wheels[@]} -ne 16 || ${#sdists[@]} -ne 1 ]]; then + echo "Expected 16 wheels and 1 sdist in dist/, got ${#wheels[@]} wheel(s) and ${#sdists[@]} sdist(s)." >&2 + exit 1 + fi + for w in "${wheels[@]}"; do + if [[ "$(basename "$w")" != wavefactor-"$VERSION"-* ]]; then + echo "Wheel $w does not match VERSION $VERSION" >&2 + exit 1 + fi + done + if [[ "$(basename "${sdists[0]}")" != "wavefactor-$VERSION.tar.gz" ]]; then + echo "sdist ${sdists[0]} does not match VERSION $VERSION" >&2 + exit 1 + fi + echo "RELEASE_TAG=v$VERSION" >> "$GITHUB_ENV" + shell: bash + + # Never attach artifacts built from this commit to a tag that points at different code + # (e.g. an already-released version whose VERSION was not bumped). + - name: Guard release tag provenance + run: | + set -euo pipefail + if git rev-parse -q --verify "refs/tags/${RELEASE_TAG}" > /dev/null; then + TAG_SHA=$(git rev-list -n 1 "refs/tags/${RELEASE_TAG}") + if [[ "$TAG_SHA" != "$GITHUB_SHA" ]]; then + echo "::error::Tag ${RELEASE_TAG} already exists at ${TAG_SHA}, but this build is from ${GITHUB_SHA}. Bump VERSION to a new version before releasing." + exit 1 + fi + echo "Tag ${RELEASE_TAG} already exists at this commit; continuing (re-run)." + else + echo "Tag ${RELEASE_TAG} does not exist yet; it will be created at ${GITHUB_SHA}." + fi + shell: bash + + - name: Publish package distributions to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: dist/ + # Makes re-runs idempotent if a later step (e.g. the GitHub Release) failed previously + skip-existing: true + + - name: Create or update GitHub Release with artifacts + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TARGET_SHA: ${{ github.sha }} + run: | + set -euo pipefail + flags=() + if [[ "$RELEASE_TAG" =~ (a|b|rc|dev)[0-9]+$ ]]; then + flags+=(--prerelease) + fi + if gh release view "$RELEASE_TAG" >/dev/null 2>&1; then + echo "Release $RELEASE_TAG already exists. Uploading distribution assets..." + gh release upload "$RELEASE_TAG" --clobber -- dist/* + else + echo "Creating GitHub Release $RELEASE_TAG at $TARGET_SHA with distribution assets..." + gh release create "$RELEASE_TAG" --target "$TARGET_SHA" --title "$RELEASE_TAG" --generate-notes "${flags[@]}" -- dist/* + fi + shell: bash diff --git a/.gitignore b/.gitignore index f0a5226..b186c94 100644 --- a/.gitignore +++ b/.gitignore @@ -48,6 +48,9 @@ out/ build/ *.pyd *.so +dist/ +*.egg-info/ +site/ # Not typical practice to include installable libraries; but here kept for sake of ease of reproducibility (hence below commented out) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0eac38c..ec379f5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,29 +6,92 @@ set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_POSITION_INDEPENDENT_CODE ON) -# Optimization flags (portable -O3 by default, optional AVX2/FMA and -march=native) -option(ENABLE_AVX2 "Enable AVX2 and FMA vectorization instructions" ON) +# Optimization flags (portable -O3 on GCC/Clang, automatic AVX2/FMA detection with fallback, optional -march=native) +option(ENABLE_AVX2 "Enable AVX2 and FMA vectorization instructions when supported" ON) option(ENABLE_NATIVE_TUNING "Enable host CPU architecture tuning (-march=native)" OFF) -set(WAVEFACTOR_COMPILE_OPTIONS -O3) + +set(WAVEFACTOR_COMPILE_OPTIONS "") +if(NOT MSVC) + list(APPEND WAVEFACTOR_COMPILE_OPTIONS "$<$>:-O3>") +endif() + if(ENABLE_AVX2) if(MSVC) - list(APPEND WAVEFACTOR_COMPILE_OPTIONS /arch:AVX2) + set(_WAVEFACTOR_AVX2_REQ_FLAGS "/arch:AVX2") + set(_WAVEFACTOR_AVX2_LIST_FLAGS /arch:AVX2) + else() + set(_WAVEFACTOR_AVX2_REQ_FLAGS "-mavx2 -mfma") + set(_WAVEFACTOR_AVX2_LIST_FLAGS -mavx2 -mfma) + endif() + + set(_WAVEFACTOR_AVX2_TEST_SRC " + #include + int main() { + __m256d a = _mm256_set1_pd(1.0); + __m256d b = _mm256_set1_pd(2.0); + __m256d c = _mm256_fmadd_pd(a, b, a); + double out[4]; + _mm256_storeu_pd(out, c); + return (out[0] == 3.0) ? 0 : 1; + } + ") + + include(CMakePushCheckState) + cmake_push_check_state(RESET) + set(CMAKE_REQUIRED_FLAGS "${_WAVEFACTOR_AVX2_REQ_FLAGS}") + if(CMAKE_CROSSCOMPILING) + include(CheckCXXSourceCompiles) + check_cxx_source_compiles("${_WAVEFACTOR_AVX2_TEST_SRC}" WAVEFACTOR_HAS_AVX2) + else() + include(CheckCXXSourceRuns) + check_cxx_source_runs("${_WAVEFACTOR_AVX2_TEST_SRC}" WAVEFACTOR_HAS_AVX2) + endif() + cmake_pop_check_state() + + if(WAVEFACTOR_HAS_AVX2) + list(APPEND WAVEFACTOR_COMPILE_OPTIONS ${_WAVEFACTOR_AVX2_LIST_FLAGS}) + message(STATUS "WaveFactor: AVX2/FMA acceleration enabled (${_WAVEFACTOR_AVX2_REQ_FLAGS})") else() - list(APPEND WAVEFACTOR_COMPILE_OPTIONS -mavx2 -mfma) + message(STATUS "WaveFactor: AVX2/FMA unavailable on target; falling back to baseline instructions") endif() endif() -if(ENABLE_NATIVE_TUNING) - list(APPEND WAVEFACTOR_COMPILE_OPTIONS -march=native) + +if(ENABLE_NATIVE_TUNING AND NOT MSVC) + include(CheckCXXCompilerFlag) + check_cxx_compiler_flag("-march=native" WAVEFACTOR_HAS_MARCH_NATIVE) + if(WAVEFACTOR_HAS_MARCH_NATIVE) + list(APPEND WAVEFACTOR_COMPILE_OPTIONS -march=native) + endif() +endif() + +# Subdirectories for vendored libraries (isolated from user/system CMake registries) +option(BUILD_CPP_TESTS "Build C++ GoogleTest suite" ON) +set(CMAKE_EXPORT_PACKAGE_REGISTRY OFF) +set(EIGEN_BUILD_TESTING OFF CACHE BOOL "" FORCE) +set(EIGEN_BUILD_DOC OFF CACHE BOOL "" FORCE) +set(EIGEN_BUILD_DEMOS OFF CACHE BOOL "" FORCE) +set(EIGEN_BUILD_BLAS OFF CACHE BOOL "" FORCE) +set(EIGEN_BUILD_LAPACK OFF CACHE BOOL "" FORCE) +set(EIGEN_BUILD_PKGCONFIG OFF CACHE BOOL "" FORCE) +set(EIGEN_BUILD_CMAKE_PACKAGE OFF CACHE BOOL "" FORCE) + +# MSVC only exposes M_PI (used throughout src/) when _USE_MATH_DEFINES is defined +if(MSVC) + add_compile_definitions(_USE_MATH_DEFINES) endif() -# Subdirectories for libraries +add_subdirectory(lib/eigen EXCLUDE_FROM_ALL) add_subdirectory(src) -add_subdirectory(lib/googletest) -add_subdirectory(lib/eigen) # Enable testing for C++ GoogleTest suite -enable_testing() -add_subdirectory(test) +if(BUILD_CPP_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/lib/googletest/CMakeLists.txt") + set(INSTALL_GTEST OFF CACHE BOOL "" FORCE) + # Use the shared MSVC runtime so GoogleTest links against the (/MD) WaveFactorSrc library + set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) + add_subdirectory(lib/googletest EXCLUDE_FROM_ALL) + enable_testing() + add_subdirectory(test) +endif() # Headers and Sources for Pybind11 extension module set(Headers @@ -58,29 +121,26 @@ option(BUILD_PYTHON_MODULE "Build Python Pybind11 extension module" ON) if(BUILD_PYTHON_MODULE) set(PYBIND11_FINDPYTHON ON CACHE BOOL "Use FindPython mode in pybind11" FORCE) - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/lib/pybind11/CMakeLists.txt") - add_subdirectory(lib/pybind11) - else() - find_package(pybind11 CONFIG QUIET) + if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/lib/pybind11/CMakeLists.txt") + message(FATAL_ERROR "Vendored pybind11 not found at lib/pybind11/CMakeLists.txt") endif() + add_subdirectory(lib/pybind11 EXCLUDE_FROM_ALL) - if(TARGET pybind11::module OR TARGET pybind11::pybind11) - pybind11_add_module(WaveFactor SHARED ${Sources} ${Headers}) - target_link_libraries(WaveFactor PRIVATE eigen) - target_include_directories(WaveFactor PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + pybind11_add_module(WaveFactor MODULE ${Sources} ${Headers}) + target_link_libraries(WaveFactor PRIVATE eigen) + target_include_directories(WaveFactor PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - # Optimization flags - target_compile_options(WaveFactor PRIVATE ${WAVEFACTOR_COMPILE_OPTIONS}) + # Optimization flags + target_compile_options(WaveFactor PRIVATE ${WAVEFACTOR_COMPILE_OPTIONS}) - # Static linking of GCC/MinGW runtimes on Windows to avoid external DLL dependencies - if(MINGW) - target_link_options(WaveFactor PRIVATE -static-libgcc -static-libstdc++) - endif() + # Static linking of GCC/MinGW runtimes on Windows to avoid external DLL dependencies + if(MINGW) + target_link_options(WaveFactor PRIVATE -static-libgcc -static-libstdc++) + endif() - # Create __init__.py in binary directory for testing direct imports from build - set(INIT_PY "${CMAKE_CURRENT_BINARY_DIR}/__init__.py") - if(NOT EXISTS ${INIT_PY}) - file(WRITE ${INIT_PY} "") - endif() + # Create __init__.py in binary directory for testing direct imports from build + set(INIT_PY "${CMAKE_CURRENT_BINARY_DIR}/__init__.py") + if(NOT EXISTS ${INIT_PY}) + file(WRITE ${INIT_PY} "") endif() -endif() \ No newline at end of file +endif() diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..e854fab --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,26 @@ +include README.md +include LICENSE +include VERSION +include CMakeLists.txt +include pyproject.toml +include setup.py + +recursive-include src *.hpp *.cpp CMakeLists.txt +recursive-include lib/eigen * +recursive-include lib/pybind11 * +recursive-include lib/googletest * +recursive-include test * +recursive-include wavefactor *.py +recursive-include tests *.py *.csv *.npz + +prune lib/eigen/test +prune lib/eigen/failtest +prune lib/eigen/bench +prune lib/eigen/doc +prune lib/eigen/demos +prune lib/pybind11/tests +prune lib/pybind11/docs +prune lib/googletest/googletest/test +prune lib/googletest/googlemock/test + +global-exclude *.py[cod] __pycache__ *.so *.pyd *.dylib .git* .DS_Store diff --git a/pyproject.toml b/pyproject.toml index bb828d7..11de39a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["setuptools>=61.0", "wheel", "pybind11>=2.6.0"] +requires = ["setuptools>=77.0.0", "wheel", "cmake>=3.20"] build-backend = "setuptools.build_meta" [project] @@ -7,13 +7,17 @@ name = "wavefactor" dynamic = ["version"] description = "Bayesian Multiresolution Wavelet Spatial Factor Model for Spatial Transcriptomics" readme = "README.md" -requires-python = ">=3.7" -license = { text = "MIT" } +requires-python = ">=3.10" +license = "GPL-3.0-or-later" +# Bundle the licences of the vendored libraries compiled into the binary wheels +license-files = [ + "LICENSE", + "lib/pybind11/LICENSE", + "lib/eigen/COPYING.MPL2", + "lib/eigen/COPYING.BSD", +] classifiers = [ "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -41,3 +45,16 @@ include = ["wavefactor*"] [tool.setuptools.dynamic] version = {file = "VERSION"} + +[tool.cibuildwheel] +# Build CPython 3.10 - 3.13 binary wheels +build = ["cp310-*", "cp311-*", "cp312-*", "cp313-*"] +# Skip 32-bit platforms, PyPy, and musllinux +skip = ["*-win32", "*-manylinux_i686", "pp*", "*musllinux*"] + +# Test every built wheel in an isolated environment before packaging +test-requires = ["pytest>=7.0.0"] +test-command = "pytest {project}/tests" + +[tool.cibuildwheel.linux] +manylinux-x86_64-image = "manylinux_2_28" diff --git a/setup.py b/setup.py index 5dd3b4b..8beb295 100644 --- a/setup.py +++ b/setup.py @@ -7,12 +7,60 @@ import os import sys +import shlex import shutil +import sysconfig import subprocess from setuptools import setup, Extension from setuptools.command.build_ext import build_ext +def _should_use_mingw() -> bool: + """Detect whether MinGW Makefiles should be used on Windows.""" + if sys.platform != "win32": + return False + if os.environ.get("CMAKE_GENERATOR"): + return "MinGW" in os.environ["CMAKE_GENERATOR"] + if os.environ.get("USE_MINGW"): + return True + if os.environ.get("CIBUILDWHEEL") or shutil.which("cl"): + return False + + # Prefer MSVC when Visual Studio C++ build tools are installed + prog_files = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles", "") + vswhere = os.path.join(prog_files, "Microsoft Visual Studio", "Installer", "vswhere.exe") + if os.path.isfile(vswhere): + res = subprocess.run( + [ + vswhere, + "-latest", + "-requires", + "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", + "-property", + "installationPath", + ], + capture_output=True, + text=True, + check=False, + ) + if res.returncode == 0 and res.stdout.strip(): + return False + + # Fall back to MinGW Makefiles on local Windows machines that only have MinGW installed + return shutil.which("mingw32-make") is not None + + +def _split_cmake_args(raw_args: str): + """Split CMAKE_ARGS safely across POSIX and Windows without stripping Windows backslashes.""" + tokens = shlex.split(raw_args, posix=(os.name != "nt")) + if os.name == "nt": + tokens = [ + t[1:-1] if len(t) >= 2 and t[0] == t[-1] and t[0] in ('"', "'") else t + for t in tokens + ] + return tokens + + class CMakeExtension(Extension): """A setuptools Extension that delegates compilation to CMake.""" def __init__(self, name, sourcedir=""): @@ -21,66 +69,102 @@ def __init__(self, name, sourcedir=""): class CMakeBuild(build_ext): - """Build extension that invokes CMake to compile targets.""" + """Build extension that invokes CMake in an isolated temporary build directory.""" def build_extension(self, ext): - extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) + ext_fullpath = os.path.abspath(self.get_ext_fullpath(ext.name)) + extdir = os.path.dirname(ext_fullpath) os.makedirs(extdir, exist_ok=True) - repo_build = os.path.join(ext.sourcedir, "build") - - # 1. If an active configured build/ directory exists, build target directly - if os.path.isfile(os.path.join(repo_build, "CMakeCache.txt")): - subprocess.check_call(["cmake", "--build", repo_build, "--target", ext.name]) - self._copy_built_binary(repo_build, extdir, ext.name) - return - - # 2. Otherwise configure and build in self.build_temp - build_temp = os.path.join(self.build_temp, ext.name) - os.makedirs(build_temp, exist_ok=True) - debug = int(os.environ.get("DEBUG", 0)) if self.debug is None else self.debug cfg = "Debug" if debug else "Release" + build_temp = os.path.abspath(os.path.join(self.build_temp, ext.name)) + os.makedirs(build_temp, exist_ok=True) + cmake_args = [ f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}", f"-DCMAKE_RUNTIME_OUTPUT_DIRECTORY={extdir}", + f"-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY={build_temp}", + f"-DPython_EXECUTABLE={sys.executable}", + f"-DPython3_EXECUTABLE={sys.executable}", f"-DPYTHON_EXECUTABLE={sys.executable}", - f"-DCMAKE_BUILD_TYPE={cfg}", "-DBUILD_PYTHON_MODULE=ON", + "-DBUILD_CPP_TESTS=OFF", ] - if sys.platform == "win32": + build_args = ["--target", ext.name] + + use_mingw = _should_use_mingw() + cmake_generator = os.environ.get("CMAKE_GENERATOR", "") + if use_mingw and not cmake_generator: cmake_args.extend(["-G", "MinGW Makefiles"]) + is_multi_config = False + elif sys.platform == "win32": + is_multi_config = ( + (not cmake_generator) + or ("Visual Studio" in cmake_generator) + or ("Multi-Config" in cmake_generator) + ) + else: + is_multi_config = "Multi-Config" in cmake_generator + + if is_multi_config: + cfg_upper = cfg.upper() + cmake_args.extend([ + f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{cfg_upper}={extdir}", + f"-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{cfg_upper}={extdir}", + f"-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY_{cfg_upper}={build_temp}", + ]) + build_args.extend(["--config", cfg]) + else: + cmake_args.append(f"-DCMAKE_BUILD_TYPE={cfg}") + + if "CMAKE_ARGS" in os.environ: + cmake_args.extend(_split_cmake_args(os.environ["CMAKE_ARGS"])) + + if "CMAKE_BUILD_PARALLEL_LEVEL" not in os.environ: + build_args.append("--parallel") subprocess.check_call(["cmake", ext.sourcedir] + cmake_args, cwd=build_temp) - subprocess.check_call(["cmake", "--build", ".", "--target", ext.name], cwd=build_temp) + subprocess.check_call(["cmake", "--build", "."] + build_args, cwd=build_temp) self._copy_built_binary(build_temp, extdir, ext.name) + if not os.path.isfile(ext_fullpath): + raise RuntimeError( + f"CMake build completed, but expected compiled extension binary was not found at: {ext_fullpath}" + ) + def _copy_built_binary(self, src_dir, dest_dir, target_name): - """Copies the compiled .pyd / .so extension to the target destination if needed.""" + """Copies the compiled .pyd / .so extension matching the active Python ABI if needed.""" src_dir = os.path.abspath(src_dir) dest_dir = os.path.abspath(dest_dir) if src_dir == dest_dir: return + ext_suffix = sysconfig.get_config_var("EXT_SUFFIX") or "" + expected_exact = f"{target_name}{ext_suffix}" if ext_suffix else None + + fallback_match = None for root, _, files in os.walk(src_dir): for f in files: - if f.startswith(target_name) and (f.endswith(".pyd") or f.endswith(".so")): - src_file = os.path.join(root, f) - dest_file = os.path.join(dest_dir, f) - if not os.path.exists(dest_file) or os.path.getmtime(src_file) > os.path.getmtime(dest_file): - shutil.copy2(src_file, dest_file) + if expected_exact and f == expected_exact: + self._copy_if_newer(os.path.join(root, f), os.path.join(dest_dir, f)) return + if fallback_match is None and f.startswith(target_name) and f.endswith((".pyd", ".so", ".dylib")): + fallback_match = (os.path.join(root, f), os.path.join(dest_dir, f)) + if fallback_match is not None: + self._copy_if_newer(*fallback_match) -with open(os.path.join(os.path.dirname(__file__), "VERSION"), "r", encoding="utf-8") as f: - version = f.read().strip() + @staticmethod + def _copy_if_newer(src_file, dest_file): + if os.path.abspath(src_file) == os.path.abspath(dest_file): + return + if not os.path.exists(dest_file) or os.path.getmtime(src_file) > os.path.getmtime(dest_file): + shutil.copy2(src_file, dest_file) setup( - name="wavefactor", - version=version, - packages=["wavefactor"], ext_modules=[CMakeExtension("WaveFactor")], cmdclass={"build_ext": CMakeBuild}, ) diff --git a/tests/compat.py b/tests/compat.py deleted file mode 100644 index 24ca617..0000000 --- a/tests/compat.py +++ /dev/null @@ -1,32 +0,0 @@ -""" -Compatibility layer for running tests when pytest is not installed. -""" - -try: - import pytest -except ImportError: - class _RaisesContext: - def __init__(self, expected_exc, match=None): - self.expected_exc = expected_exc - self.match = match - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - if exc_type is None: - raise AssertionError(f"Expected exception {self.expected_exc} was not raised.") - if not issubclass(exc_type, self.expected_exc): - return False - if self.match is not None and self.match not in str(exc_val): - raise AssertionError(f"Pattern '{self.match}' not found in '{str(exc_val)}'") - return True - - class _PytestFallback: - def raises(self, expected_exc, *args, **kwargs): - match = kwargs.get("match", None) - return _RaisesContext(expected_exc, match=match) - - pytest = _PytestFallback() - -__all__ = ["pytest"] diff --git a/tests/test_data.py b/tests/test_data.py index 900e91f..7be2f78 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -2,7 +2,7 @@ Unit tests for wavefactor.data (spatial data preparation, gridding, and 2D DWT). """ -from tests.compat import pytest +import pytest import numpy as np import pandas as pd from wavefactor.data import prepare_spatial_data, is_power_of_4, get_L_shape, get_Y_shape diff --git a/tests/test_model.py b/tests/test_model.py index befbf6b..0d6c67f 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -2,7 +2,7 @@ Integration tests for WaveFactor estimator and WaveFactorResult. """ -from tests.compat import pytest +import pytest import numpy as np from wavefactor import WaveFactor, WaveFactorResult from wavefactor.engine import init_parameters diff --git a/tests/test_priors.py b/tests/test_priors.py index 22c8c74..3f7b47b 100644 --- a/tests/test_priors.py +++ b/tests/test_priors.py @@ -2,7 +2,7 @@ Unit tests for wavefactor.priors. """ -from tests.compat import pytest +import pytest import numpy as np from wavefactor.priors import Priors from wavefactor.data import _build_dimensions_dict diff --git a/tests/test_reference_parity.py b/tests/test_reference_parity.py index 5e651bb..8a6bd2f 100644 --- a/tests/test_reference_parity.py +++ b/tests/test_reference_parity.py @@ -9,7 +9,7 @@ import numpy as np import pandas as pd import pywt -from tests.compat import pytest + from wavefactor import WaveFactor, WaveFactorResult from wavefactor.data import prepare_spatial_data diff --git a/wavefactor/__init__.py b/wavefactor/__init__.py index d8010b4..3cbfe20 100644 --- a/wavefactor/__init__.py +++ b/wavefactor/__init__.py @@ -8,8 +8,9 @@ def _load_version() -> str: """Loads WaveFactor package version from repository root or package metadata.""" # 1. Dev mode: read language-neutral VERSION asset directly from repository root - repo_version_file = Path(__file__).resolve().parent.parent / "VERSION" - if repo_version_file.is_file(): + repo_root = Path(__file__).resolve().parent.parent + repo_version_file = repo_root / "VERSION" + if repo_version_file.is_file() and (repo_root / "CMakeLists.txt").is_file(): return repo_version_file.read_text(encoding="utf-8").strip() # 2. Installed mode: read from package metadata when distributed as a wheel From 47a3e359e2186c9d6085c509856ba7e5a470dc93 Mon Sep 17 00:00:00 2001 From: Yulin-W <65204338+Yulin-W@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:21:54 +1100 Subject: [PATCH 2/2] docs: update docs regarding prebuild wheel installation --- README.md | 16 ++++++++++ docs/getting_started.md | 2 -- docs/index.md | 18 +++++++++++- docs/input_output.md | 4 --- docs/installation.md | 65 +++++++++++++++++------------------------ 5 files changed, 59 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 35e0458..4cd6477 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,22 @@ --- +## Quick Install + +Install WaveFactor with pip: + +```bash +pip install wavefactor +``` + +Verify your installation: + +```bash +python -c "import wavefactor as wf; print('WaveFactor version:', wf.__version__)" +``` + +--- + ## Documentation Please refer to the [documentation](https://shimlab.github.io/WaveFactor/) for installation, code snippets, examples, etc. diff --git a/docs/getting_started.md b/docs/getting_started.md index 4421efc..dd88a0e 100644 --- a/docs/getting_started.md +++ b/docs/getting_started.md @@ -1,7 +1,5 @@ # Getting Started -> **Note**: This documentation is a **work in progress** and subject to further improvements. - First, follow **[Installation Guide](installation.md)** to install WaveFactor into a virtual environment and activate said environment. ## Example Code Snippet diff --git a/docs/index.md b/docs/index.md index c488100..c75f87e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -7,9 +7,25 @@ --- +## Quick Install + +Install WaveFactor with pip: + +```bash +pip install wavefactor +``` + +Verify your installation: + +```bash +python -c "import wavefactor as wf; print('WaveFactor version:', wf.__version__)" +``` + +--- + ## Contents -- **[Installation Guide](installation.md)**: How to set up an isolated environment and install WaveFactor. +- **[Installation Guide](installation.md)**: Detailed installation options - **[Data Input & Output](input_output.md)**: Expected input grid formats, preprocessing tips, and model outputs. - **[Getting Started Example](getting_started.md)**: How to run the quick self-contained simulation. diff --git a/docs/input_output.md b/docs/input_output.md index ee9bc46..50027c8 100644 --- a/docs/input_output.md +++ b/docs/input_output.md @@ -1,9 +1,5 @@ # Data Input & Output -> **Note**: This documentation is a **work in progress** and subject to further improvements. - ---- - ## 1. What WaveFactor Expects as Input WaveFactor needs two inputs: an expression matrix `X` and spot coordinates `coords`. diff --git a/docs/installation.md b/docs/installation.md index fea5f11..0d3e76b 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -1,60 +1,47 @@ # Installation Guide -> **Note**: This documentation is a **work in progress** and subject to further improvements. +## Standard Installation (Recommended) ---- - -## 1. Requirements - -Before installing, make sure you have: - -- **Python** $\ge 3.7$ -- **CMake** $\ge 3.16$ -- **A C++17 compiler** (e.g. GCC or Clang) - ---- - -## 2. Install in an Isolated Environment - -Using an isolated virtual environment prevents conflicts with other Python packages: +Install WaveFactor with pip: ```bash -# 1. Clone this repository (copy URL from the green "Code" button on GitHub) -git clone https://github.com/shimlab/WaveFactor.git -cd WaveFactor +pip install wavefactor +``` -# 2. Create and activate a virtual environment (this might differ depending on Python setup/operating system, etc.) -python3 -m venv wavefactor-venv -source wavefactor-venv/bin/activate +Verify your installation: -# 3. Install WaveFactor -pip install . +```bash +python -c "import wavefactor as wf; print('WaveFactor version:', wf.__version__)" ``` -> **Warning** if installing into multiple environments or reinstalling, we recommend deleting the `build` folder created after every installation before starting a new installation so as to avoid potential conflicts with installation artifacts. +!!! tip "Ready-to-Use Packages (Pre-Compiled)" + Ready-to-use packages are provided for standard modern Python installations (**Python 3.10, 3.11, 3.12, and 3.13**) across common platforms (**Linux**, **Windows**, and **Mac**). ---- + If these packages do not work for you, you can also try building from source (see below). -## 3. (Optional) Check Installation Succeeded +--- -Check that the installation succeeded: +## Optional: Building from Source -```bash -pip show wavefactor -``` +If a pre-compiled wheel is not available or fails for your environment or you wish to compile locally: ---- +### Prerequisites -## 4. (Optional) Deactivate or Remove +These are illustrative reference settings rather than rigid constraints—other configurations may also work, though meeting them does not guarantee successful builds across arbitrary systems: -Deactivate the virtual environment by: +- **Python** $\ge 3.10$ +- **CMake** $\ge 3.20$ +- **A C++17 compiler** (e.g. GCC, Clang, or MSVC) -```bash -deactivate -``` +### Instructions -After deactivation, to completely delete the installation, just remove the `wavefactor-venv/` folder: +Clone the repository and install using `pip`: ```bash -rm -rf wavefactor-venv +# 1. Clone this repository +git clone https://github.com/shimlab/WaveFactor.git +cd WaveFactor + +# 2. Build and install locally +pip install . ```