Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ SET(SHAPEWORKS_PATCH_VERSION 0 CACHE INTERNAL "Patch version number" FORCE)
SET(SHAPEWORKS_VERSION_STRING "6.9.0-dev")
SET(SHAPEWORKS_VERSION "${SHAPEWORKS_MAJOR_VERSION}.${SHAPEWORKS_MINOR_VERSION}.${SHAPEWORKS_PATCH_VERSION}")

# Python API version: names the per-user site-packages dir and must match the Python package
set(SHAPEWORKS_PYTHON_API_VERSION "${SHAPEWORKS_MAJOR_VERSION}.${SHAPEWORKS_MINOR_VERSION}")
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/Python/shapeworks/shapeworks/api_version.py" _py_api_line
REGEX "^API_VERSION = ")
if (NOT _py_api_line STREQUAL "API_VERSION = \"${SHAPEWORKS_PYTHON_API_VERSION}\"")
message(FATAL_ERROR "Python/shapeworks/shapeworks/api_version.py (${_py_api_line}) does not match "
"SHAPEWORKS_MAJOR/MINOR_VERSION (${SHAPEWORKS_PYTHON_API_VERSION})")
endif()
add_compile_definitions(SHAPEWORKS_PYTHON_API_VERSION="${SHAPEWORKS_PYTHON_API_VERSION}")

# First, check that files were checked out properly using git-lfs
file(MD5 "${CMAKE_CURRENT_SOURCE_DIR}/Testing/data/icp_baseline.nrrd" HASH)
if (NOT "${HASH}" STREQUAL "bb94438a695c749b264180019abbbb97")
Expand Down
2 changes: 1 addition & 1 deletion Libs/Application/Job/PythonWorker.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class PythonWorker : public QObject {
Q_OBJECT

public:
constexpr static const char* python_api_version = "6.9";
constexpr static const char* python_api_version = SHAPEWORKS_PYTHON_API_VERSION;

PythonWorker();
~PythonWorker();
Expand Down
4 changes: 4 additions & 0 deletions Python/shapeworks/shapeworks/api_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# ShapeWorks Python API version (major.minor). It names the per-user site-packages
# directory used for on-demand installs (PyTorch, swpip) and is checked by Studio
# against the C++ side. CMake verifies it matches SHAPEWORKS_MAJOR/MINOR_VERSION.
API_VERSION = "6.9"
56 changes: 33 additions & 23 deletions Python/shapeworks/shapeworks/network_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,38 @@
import shapeworks as sw
np.random.seed(0)

# open3d is imported lazily when needed (not available on all platforms)

def compute_particle_triangles(surface, points, min_vertices_per_point=10):
"""Triangulate particles over a surface mesh.

Each surface vertex is labeled with its nearest particle, partitioning the surface into
discrete Voronoi regions. Every surface triangle whose three vertices belong to three
different particles becomes a particle triangle, so particles are connected when their
regions meet on the surface.
"""
triangle_filter = vtk.vtkTriangleFilter()
triangle_filter.SetInputData(surface)
triangle_filter.Update()
mesh = triangle_filter.GetOutput()

# refine the surface until it is fine enough to resolve the regions
for _ in range(4):
if mesh.GetNumberOfPoints() >= min_vertices_per_point * len(points):
break
subdivide = vtk.vtkLinearSubdivisionFilter()
subdivide.SetInputData(mesh)
subdivide.SetNumberOfSubdivisions(1)
subdivide.Update()
mesh = subdivide.GetOutput()

vertices = vtk_to_numpy(mesh.GetPoints().GetData())
faces = vtk_to_numpy(mesh.GetPolys().GetConnectivityArray()).reshape(-1, 3)

labels = scipy.spatial.cKDTree(points).query(vertices)[1]
face_labels = labels[faces]
distinct = ((face_labels[:, 0] != face_labels[:, 1]) & (face_labels[:, 1] != face_labels[:, 2]) &
(face_labels[:, 0] != face_labels[:, 2]))
return np.unique(np.sort(face_labels[distinct], axis=1), axis=0)


class NetworkAnalysis:
Expand Down Expand Up @@ -86,16 +117,6 @@ def compute_mean_shape(self):
return mesh_points, mesh_normals, mean_shape, surface

def run(self):
# Import open3d here (lazy import - not available on all platforms)
try:
import open3d as o3d
except ImportError:
raise ImportError(
"open3d is required for network analysis but is not installed. "
"This feature may not be available on your platform/Python version. "
"Try: pip install open3d-cpu (Linux) or pip install open3d (macOS/Windows)"
)

project = self.project
analyze = self.analyze
num_pts = analyze.get_num_particles()
Expand Down Expand Up @@ -359,18 +380,7 @@ def run(self):
# In[15]:

# generate connectivity between particles
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(mean_shape[particles, :])
pcd.normals = o3d.utility.Vector3dVector(mesh_normals[pts_index, :])

distances = pcd.compute_nearest_neighbor_distance()
avg_dist = np.mean(distances)
radius = avg_dist * 1.5

mesh = o3d.geometry.TriangleMesh.create_from_point_cloud_ball_pivoting(pcd,
o3d.utility.DoubleVector(
[radius, radius * 2]))
tris = np.asarray(mesh.triangles)
tris = compute_particle_triangles(surface, mean_shape[particles, :])

# In[16]:

Expand Down
4 changes: 1 addition & 3 deletions Python/shapeworks/shapeworks/torch_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@
import subprocess
import sys

# Must match PythonWorker::python_api_version in Libs/Application/Job/PythonWorker.h.
# Bump alongside SW_MAJOR_VERSION / SW_MINOR_VERSION per docs/dev/release-checklist.
_API_VERSION = "6.8"
from .api_version import API_VERSION as _API_VERSION


def _user_site_packages():
Expand Down
3 changes: 2 additions & 1 deletion Python/shapeworks/shapeworks/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import shutil
import zipfile
import shapeworks as sw
from shapeworks.api_version import API_VERSION

# Global shapeworks logger object (e.g. attached to Studio)
sw_logger = None
Expand Down Expand Up @@ -172,7 +173,7 @@ def compute_line_indices(n, is_closed=True):


def get_api_version():
return "6.9"
return API_VERSION


def set_sw_logger(log_object):
Expand Down
11 changes: 5 additions & 6 deletions cmake/BundledPython.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -257,9 +257,8 @@ if(WIN32)
"@echo off
set \"PYTHONHOME=${BUNDLED_PYTHON_ROOT}\"
rem Build dir for shapeworks_py + per-user site-packages for on-demand torch
rem / swpip installs. Version segment must match python_api_version in
rem PythonWorker.h.
set \"PYTHONPATH=${CMAKE_BINARY_DIR}/bin;%LOCALAPPDATA%\\ShapeWorks\\6.8\\site-packages\"
rem / swpip installs.
set \"PYTHONPATH=${CMAKE_BINARY_DIR}/bin;%LOCALAPPDATA%\\ShapeWorks\\${SHAPEWORKS_PYTHON_API_VERSION}\\site-packages\"
set \"PATH=${CMAKE_BINARY_DIR}/bin;%PATH%\"
if not defined MPLBACKEND set \"MPLBACKEND=Agg\"
\"${BUNDLED_PYTHON_EXECUTABLE}\" %*
Expand All @@ -271,11 +270,11 @@ else()
export PYTHONHOME='${BUNDLED_PYTHON_ROOT}'
# Build dir for shapeworks_py + per-user site-packages for on-demand torch /
# swpip installs. The per-user path is platform-dependent so derive it at
# runtime. Version segment must match python_api_version in PythonWorker.h.
# runtime.
if [ \"\$(uname)\" = \"Darwin\" ]; then
_sw_user_site=\"\$HOME/Library/Application Support/ShapeWorks/6.8/site-packages\"
_sw_user_site=\"\$HOME/Library/Application Support/ShapeWorks/${SHAPEWORKS_PYTHON_API_VERSION}/site-packages\"
else
_sw_user_site=\"\$HOME/.local/share/ShapeWorks/6.8/site-packages\"
_sw_user_site=\"\$HOME/.local/share/ShapeWorks/${SHAPEWORKS_PYTHON_API_VERSION}/site-packages\"
fi
export PYTHONPATH=\"${CMAKE_BINARY_DIR}/bin:\$_sw_user_site\"
export PATH='${CMAKE_BINARY_DIR}/bin':\"\$PATH\"
Expand Down
25 changes: 14 additions & 11 deletions cmake/InstallBundledPython.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -157,19 +157,20 @@ install(CODE "
# can find the shapeworks CLI via shutil.which.
set(_swpython_dir "${CMAKE_BINARY_DIR}/_bundled_python/swpython")
file(MAKE_DIRECTORY "${_swpython_dir}")
file(WRITE "${_swpython_dir}/swpython.bat"
set(_wrapper_content
[=[@echo off
set "LOC=%~dp0"
set "PYTHONHOME=%LOC%..\lib\python"
set "PATH=%LOC%;%PATH%"
rem Put the per-user ShapeWorks site-packages on PYTHONPATH so on-demand-
rem installed PyTorch and swpip-installed packages are importable from any
rem `swpython script.py`, not only after `from shapeworks import ensure_torch`.
rem Version segment "6.8" must match python_api_version in PythonWorker.h.
set "PYTHONPATH=%LOCALAPPDATA%\ShapeWorks\6.8\site-packages"
set "PYTHONPATH=%LOCALAPPDATA%\ShapeWorks\@SHAPEWORKS_PYTHON_API_VERSION@\site-packages"
if not defined MPLBACKEND set "MPLBACKEND=Agg"
"%PYTHONHOME%\python.exe" %*
]=])
string(CONFIGURE "${_wrapper_content}" _wrapper_content @ONLY)
file(WRITE "${_swpython_dir}/swpython.bat" "${_wrapper_content}")
install(PROGRAMS "${_swpython_dir}/swpython.bat" DESTINATION bin)

# swpip.bat — pip wrapper that delegates to swpython.bat -m shapeworks.swpip
Expand Down Expand Up @@ -489,7 +490,7 @@ set(_swpython_dir "${CMAKE_BINARY_DIR}/_bundled_python/swpython")
file(MAKE_DIRECTORY "${_swpython_dir}")

if(APPLE)
file(WRITE "${_swpython_dir}/swpython"
set(_wrapper_content
[=[#!/bin/bash
LOC="`dirname "$0"`"
PYTHONHOME="${LOC}/ShapeWorksStudio.app/Contents/Resources/Python"
Expand All @@ -501,12 +502,13 @@ PATH="${LOC}:${PATH}"
MPLBACKEND="${MPLBACKEND:-Agg}"
# Put the per-user ShapeWorks site-packages on PYTHONPATH so on-demand-installed
# PyTorch and swpip-installed packages are importable from any `swpython
# script.py`, not only after `from shapeworks import ensure_torch`. Version
# segment "6.8" must match python_api_version in PythonWorker.h.
PYTHONPATH="${HOME}/Library/Application Support/ShapeWorks/6.8/site-packages"
# script.py`, not only after `from shapeworks import ensure_torch`.
PYTHONPATH="${HOME}/Library/Application Support/ShapeWorks/@SHAPEWORKS_PYTHON_API_VERSION@/site-packages"
export PYTHONHOME PATH MPLBACKEND PYTHONPATH
exec "${PYTHONHOME}/bin/python3" "$@"
]=])
string(CONFIGURE "${_wrapper_content}" _wrapper_content @ONLY)
file(WRITE "${_swpython_dir}/swpython" "${_wrapper_content}")
install(PROGRAMS "${_swpython_dir}/swpython" DESTINATION bin)

elseif(WIN32)
Expand All @@ -530,7 +532,7 @@ else()
# extension imports.
# Also prepend the bundle bin/ to PATH so `shutil.which("shapeworks")`
# in use case scripts finds the CLI sitting next to the wrapper.
file(WRITE "${_swpython_dir}/swpython"
set(_wrapper_content
[=[#!/bin/bash
LOC="`dirname "$0"`"
PYTHONHOME="${LOC}/../lib/python"
Expand All @@ -539,12 +541,13 @@ PATH="${LOC}:${PATH}"
MPLBACKEND="${MPLBACKEND:-Agg}"
# Put the per-user ShapeWorks site-packages on PYTHONPATH so on-demand-installed
# PyTorch and swpip-installed packages are importable from any `swpython
# script.py`, not only after `from shapeworks import ensure_torch`. Version
# segment "6.8" must match python_api_version in PythonWorker.h.
PYTHONPATH="${HOME}/.local/share/ShapeWorks/6.8/site-packages"
# script.py`, not only after `from shapeworks import ensure_torch`.
PYTHONPATH="${HOME}/.local/share/ShapeWorks/@SHAPEWORKS_PYTHON_API_VERSION@/site-packages"
export PYTHONHOME LD_LIBRARY_PATH PATH MPLBACKEND PYTHONPATH
exec "${PYTHONHOME}/bin/python3" "$@"
]=])
string(CONFIGURE "${_wrapper_content}" _wrapper_content @ONLY)
file(WRITE "${_swpython_dir}/swpython" "${_wrapper_content}")
install(PROGRAMS "${_swpython_dir}/swpython" DESTINATION bin)
endif()

Expand Down
13 changes: 3 additions & 10 deletions docs/dev/release-process.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,12 @@ SET(SHAPEWORKS_VERSION "${SHAPEWORKS_MAJOR_VERSION}.${SHAPEWORKS_MINOR_VERSION}.

* Confirm the API version is set correctly in the following files

TODO - This should be automated from a single place
The C++ side and the `swpython`/`swpip` wrappers derive it from `SHAPEWORKS_MAJOR/MINOR_VERSION`. CMake fails if the Python side doesn't match:

- `Libs/Application/Job/PythonWorker.h`
- `Python/shapeworks/shapeworks/api_version.py`

```
constexpr static const char* python_api_version = "6.5";
```

- `Python/shapeworks/shapeworks/utils.py`

```
def get_api_version():
return "6.5"
API_VERSION = "6.5"
```

- `install_shapeworks.sh`
Expand Down
3 changes: 0 additions & 3 deletions install_shapeworks.bat
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,6 @@ REM install pytorch using light-the-torch
REM Use python -m to ensure we use the conda env's light_the_torch
call python -m light_the_torch install torch==2.8.0 torchaudio==2.8.0 torchvision==0.23.0 || goto :error

REM different versions of open3d for different OSes, so we install it manually here
call pip install open3d==0.19.0 || goto :error

call pip install Python/DataAugmentationUtilsPackage.tar.gz || goto :error
call pip install Python/DatasetUtilsPackage.tar.gz || goto :error
call pip install Python/MONAILabelPackage.tar.gz || goto :error
Expand Down
32 changes: 0 additions & 32 deletions install_shapeworks.sh
Original file line number Diff line number Diff line change
Expand Up @@ -205,38 +205,6 @@ function install_conda() {
if ! retry python -m light_the_torch install torch==2.8.0 torchaudio==2.8.0 torchvision==0.23.0; then return 1; fi
fi

# for network analysis (optional - not available on all platforms/Python versions)
# open3d needs to be installed differently on each platform so it's not part of python_requirements.txt
OPEN3D_INSTALLED=NO
if [[ "$(uname)" == "Linux" ]]; then
if retry python -m pip install open3d-cpu==0.19.0; then
OPEN3D_INSTALLED=YES
else
echo "WARNING: open3d-cpu could not be installed. Network analysis features will not be available."
fi
elif [[ "$(uname)" == "Darwin" ]]; then
if retry python -m pip install open3d==0.19.0; then
OPEN3D_INSTALLED=YES
if [[ "$(uname -m)" == "arm64" ]]; then
pushd $CONDA_PREFIX/lib/python3.12/site-packages/open3d/cpu
install_name_tool -change /opt/homebrew/opt/libomp/lib/libomp.dylib @rpath/libomp.dylib pybind.cpython-312-darwin.so
install_name_tool -add_rpath @loader_path/../../../ pybind.cpython-312-darwin.so
# install_name_tool invalidates the signature; unsigned code is killed on load on Apple Silicon
codesign --force --sign - pybind.cpython-312-darwin.so
popd
ln -sf "$CONDA_PREFIX/lib/libomp.dylib" "$CONDA_PREFIX/lib/python3.12/site-packages/open3d/cpu/../../../libomp.dylib"
fi
else
echo "WARNING: open3d could not be installed. Network analysis features will not be available."
fi
else
if retry python -m pip install open3d==0.19.0; then
OPEN3D_INSTALLED=YES
else
echo "WARNING: open3d could not be installed. Network analysis features will not be available."
fi
fi

for package in DataAugmentationUtilsPackage DatasetUtilsPackage MONAILabelPackage DeepSSMUtilsPackage DocumentationUtilsPackage ShapeCohortGenPackage shapeworks ; do
if [[ -e Python/${package}.tar.gz ]] ; then
if ! python -m pip install Python/${package}.tar.gz; then return 1; fi
Expand Down
Loading