Repository navigation
Modernization - #43
Merged
Merged
Conversation
Use pool to parallelize stack registration, added a variable `processes` that sets the number of processes to use. If it is 1 the original code is executed if it is larger than one the parallelized code will run. note that progress_callback does not work with the parallelized version
…into gil-release
…mation calls Integrates the change proposed by @camilo1729 in issue #14 and opened as PR #33. Concurrency tests and exception-safe GIL handling are added in follow-up commits.
ASAIK using `from tqdm.auto import tqdm` results with better jupyter notebook support. @casperdcl ?
Adds deterministic synthetic test scenes with exact ground-truth transformations and a baseline of 76 result arrays (transformation matrices, landmarks and transformed images) produced by the unmodified 0.2.8 release. Subsequent changes to the native code are checked against this baseline.
- Declare metadata, dependencies and tool configuration in pyproject.toml; setup.py now only describes the C++ extension module. - Build against NumPy >= 2 (such builds also run on NumPy 1.x) and require Python >= 3.10. - Compile with -ffp-contract=off so that results do not depend on whether the target architecture fuses multiply-add operations. - Ship a py.typed marker. - Remove obsolete build helpers (setup_debug.py, build_*.sh, winbuild.bat, tox.ini, requirements.txt, .flake8), the unused C++ debug harness src/test_TurboReg.cpp and pystackreg/conftest.py, which was installed with the package and forced tests to import the source tree instead of the installed build. - Start the 0.3.0 development cycle.
…pies
Binding (src/pymain.cpp):
- Fix a reference leak: every registration leaked the three returned
arrays because they were packed with Py_BuildValue("OOO").
- Fix a NULL dereference when an input could not be converted to a
float64 array (e.g. complex data); the conversion error is now raised.
- Reject images that the native code cannot handle instead of reading
out of bounds: registration needs at least 2 x 2 pixels after cropping,
transformation at least 1 x 1, and the pixel count must fit into int.
- Reject transformation matrices that are not finite or map the image
more than 1e9 pixels away (out-of-range float-to-int conversion).
- Catch C++ exceptions (e.g. std::bad_alloc) inside the section that runs
without the GIL and translate them to Python exceptions afterwards.
- Check the allocation of the returned arrays.
- Declare the module safe for free-threaded CPython builds.
Algorithm code (no numerical change; verified bit-for-bit against the
v0.2.8 baseline):
- TurboRegTransform referenced its working images, masks and gradients
through std::vector members that were assigned by value, and the image
and mask pyramids were returned and popped by value. The Java original
stores references. These members are now non-owning pointers and the
pyramids are std::vector objects walked in place, which saves several
full-frame copies per registration.
- transform() only computes the B-spline coefficients of the image; the
gradients, pyramids and masks built before are used by the registration
only (about 3x faster for a 512 x 512 frame).
The registration converts sampling coordinates to int in 244 places with a plain C++ cast. In Java, the language of the original implementation, such a cast truncates, saturates at the int limits and maps NaN to 0. In C++ it is undefined behaviour for NaN and out-of-range values. These do occur: the optimiser produces non-finite landmark updates when the Hessian is singular, e.g. for constant images or images containing NaN. All conversions now go through toInt(), which implements the Java semantics. Results for values inside the int range are unchanged (verified bit-for-bit against the v0.2.8 baseline); degenerate inputs now follow the same well-defined path as in TurboReg on every platform, and the code is clean under UBSan (-fsanitize=undefined,float-cast-overflow).
PR #17 by Oren Amsalem introduced a 'processes' option that registers frames in a multiprocessing.Pool for the 'first' and 'mean' references. This merge records that contribution in the history without taking its code ('ours' strategy): the following commit implements the feature with threads instead of processes, which became possible once the native code releases the GIL (PR #33). Threads avoid pickling every frame to worker processes, also cover reference='previous' and transform_stack, and keep progress callbacks working.
…input validation Parallelism (issue #14, supersedes PR #17): - register_stack(), transform_stack() and register_transform_stack() take n_jobs (default 1 = sequential; -1 = all CPUs). Frames are processed in a thread pool; the native code releases the GIL, so no data is copied between processes. For reference='previous' the pairwise registrations run in parallel and are chained afterwards in frame order, so results are identical to sequential execution for every reference mode. - Worker exceptions and KeyboardInterrupt cancel outstanding frames and propagate; at most 2 * n_jobs frames are queued ahead. Progress reporting (PR #11): - tqdm.auto is imported only when verbose=True. Bars and progress callbacks are driven from the calling thread, also in parallel runs, and bars are closed when an exception occurs. transform_stack() gained verbose and progress_callback. Memory (issue #28): - transform_stack() no longer makes two transient copies of the stack and accepts out= (smaller float dtype, integer dtype with rounding and clipping, np.memmap, or the input itself for in-place operation). - The time-axis heuristic is evaluated in chunks instead of calling np.var on the whole stack, which allocated a float64 copy of it. - The moving average is computed frame by frame instead of building padded and cumulated copies of the stack. Results are unchanged for integer stacks; floating-point stacks are now averaged in double precision. Fixes: - reference='previous' with moving_average > 1 registered frame 0 to the last frame of the stack, shifting the whole result. - util.running_mean() returned an array of the wrong shape for axis != 0, so moving_average could not be combined with another frame axis. - get_matrix() before a registration raised an obscure TypeError. Validation: - Invalid arguments raise ValueError/TypeError/RuntimeError (all are subclasses of the previously raised Exception) with specific messages: wrong dimensionality or shape, images smaller than 3 x 3, empty stacks, bad n_frames/moving_average/axis, malformed matrices. - Images containing NaN or infinite values are rejected by the registration; they previously yielded an identity transformation without any notice. New API (issues #41, #42): - StackReg.transform_points() applies a transformation to (x, y) point coordinates, including the inverse of bilinear transformations. - util.max_displacement() measures the amplitude of a transformation, to detect implausible registration results. The package is fully type-annotated and checked with mypy (disallow_untyped_defs).
The suite grows from 15 to 453 test cases: - test_accuracy: recovery of known transformations for all five types on analytic scenes (corner error < 0.01 px), sub-pixel shifts, identity, matrix conventions, inverse consistency, chained stack registration, intensity invariance, and the limited capture range. - test_transform: resampling semantics, including an independent cross-check against SciPy's cubic spline interpolation, border handling and the over-/undershoot behind issues #8 and #32. - test_regression: bit-level/tight-tolerance comparison with 0.2.8. - test_stack: reference modes, frame axes, moving average, single-frame stacks, out= variants, dtypes, memory layouts, saved matrices. - test_parallel: n_jobs equivalence and determinism, concurrent use of the extension from independent threads, a check that the GIL is released, cancellation, progress callbacks and bars. - test_validation: defined errors for invalid input, including calls that bypass the Python layer. - test_points: transform_points() and util.max_displacement(). - test_imagej_reference (renamed from test_pystackreg): unchanged comparison with stacks registered in ImageJ, plus parallel runs. conftest.py reports which pystackreg is under test and, with PYSTACKREG_TEST_INSTALLED=1, refuses to test the source tree. Also keep the time-axis heuristic from emitting floating-point warnings for stacks with non-finite values (found by the new tests).
TurboReg and StackReg, of which pystackreg is a derivative work, are distributed by their author under the GNU General Public License, version 3 or later (conditions of use on the EPFL distribution pages, first archived 2023-06-04). pystackreg follows: - LICENSE now holds the unmodified text of the GPL, version 3 (replaces LICENSE.txt with the custom terms of 0.2.2 - 0.2.8). - NOTICE separates the method (Thevenaz, Ruttimann, Unser 1998), the original software (Philippe Thevenaz, EPFL) and pystackreg, reproduces the upstream conditions of use, and keeps the historical license notices for the record. Both files are installed with wheels and sdists (license-files). - Translated C++ files state the copyright of the original author and of the translation separately, carry an SPDX identifier and keep the 2011 TurboReg notice, marked as historical. Files written for pystackreg get a short header. - pyproject.toml: license = "GPL-3.0-or-later" (PEP 639). - README: attribution, citation and license sections; AUTHORS lists all contributors. Releases up to 0.2.8 remain under the terms they were published with.
…case The GIL test now counts how often a background thread runs strictly inside a single native call (a call that holds the GIL allows at most one such tick; the released GIL allows hundreds). Adds an accuracy test on a 768 x 1152 image with six pyramid levels.
- ci.yml replaces lint.yml and run-tests.yml: Ruff (lint and format), mypy and codespell; tests on Linux, Windows and macOS for Python 3.10 - 3.15 against the wheel built in the job, installed and run from outside the source tree (PYSTACKREG_TEST_INSTALLED); oldest supported NumPy and NumPy 1.26; free-threaded CPython; a job that requires bit-exact agreement with 0.2.8; a sanitizer job; sdist build with metadata and content checks; documentation build with warnings as errors. The old lint workflow pushed auto-fixes with write permission; the new jobs only read. - wheels-deploy.yml: cibuildwheel 4 on native runners for Linux x86-64 and aarch64, macOS x86-64 and arm64, Windows x86-64; every wheel is tested; distributions are checked with twine and tools/check_dist.py. Upload to PyPI happens only for pushed version tags; a manual run builds artifacts without uploading (it used to upload). - tools/check_dist.py verifies license files, license metadata, the compiled extension and the absence of test/build files in wheels. - tools/sanitize.sh builds the extension with ASan/UBSan and runs the test suite against it. - pre-commit: Ruff, mypy, codespell. Read the Docs: current build image, package installed with the docs extra. bump2version understands the .devN suffix and no longer creates tags. - sdist manifest includes tools. .gitignore covers build and tool artefacts but keeps the tracked examples/notebooks directory. The workflows have not been executed yet (no access to GitHub Actions from the development environment).
sys.getrefcount reports a different value for the same situation on CPython 3.14 and later. The test now compares with a tuple of freshly created arrays instead of a hard-coded count. Adds the Python 3.15 classifier: wheels built from the sdist pass the suite on 3.10 - 3.15.
- README: overview, scope and limitations (2D frames, not volumes; local optimizer; interpolation overshoot), supported platforms, examples for large stacks and point coordinates; removes the deleted NumPy alias np.float from the example; how to report problems, get support and contribute. - New pages: user guide (transformation models and their matrices, coordinate and direction conventions, landmarks, reference strategies, plausibility checks, limitations), performance and large stacks (threads, memory, memory-mapped data, progress reporting), validation and reproducibility, installation and troubleshooting, release procedure. - API reference lists all utility functions. - The tutorial notebook runs with current NumPy/scikit-image again and gains sections on parallel processing, the out argument, point coordinates and max_displacement; docs/tutorial.rst is regenerated from the executed notebook. - CHANGELOG entry for 0.3.0, CITATION.cff. - Sphinx: the build passes with warnings as errors; myst-parser and sphinx-autodoc-typehints are no longer needed.
- pymain.cpp: drop the Python 2 module initialisation; the package requires Python >= 3.10. - TurboRegImage.cpp, TurboRegTransform.cpp: drop the #ifdef _MSC_VER branches that worked around missing C++11 support (initializer lists, std::begin/std::end) in Visual C++ before 2015. Windows now compiles the same code as Linux and macOS. Every compiler that can build an extension for Python >= 3.10 supports it. The preprocessed sources are unchanged on Linux, so the compiled code is the same there.
…rotation and affine models targetJacobian, the normalisation of the mean squares in the scaled-rotation and affine models, is set once per pyramid level. Images with a side shorter than 24 px have no pyramid level, so the final, full-resolution stage read a value that was never set. The result depended on the contents of the stack: usually the identity, sometimes the correct transformation. Found with valgrind; ASan and UBSan do not report reads of uninitialised memory. The original has the same structure. Java initialises the field to 0.0, for which the mean squares evaluate to zero and no update is accepted: TurboReg (version "November 30, 2024") returns the identity for such images, as confirmed by running the unmodified plugin on a 16 x 16 pair. The Jacobian is now computed before the final stage when there is no pyramid level. This deviates from TurboReg for these images only. Images with both sides of at least 24 px take the unchanged code path; the 0.2.8 baseline and the results of the comparison with TurboReg are still reproduced bit for bit. tests/test_accuracy.py registers images of 12 to 23 px; the scaled-rotation and affine cases fail without the fix.
The upload job of wheels-deploy.yml used an API token stored as the repository secret PYPI_PASSWORD and installed twine into the runner's system Python. It now uses pypa/gh-action-pypi-publish with an OpenID Connect token (id-token: write) in the environment "pypi"; no secret is needed. The job still runs only for pushed version tags and only after all wheels were tested and the distributions were checked. docs/release.rst describes the one-time setup of the trusted publisher on PyPI and corrects the procedure: the changelog is committed before bump2version runs, bump2version commits the version itself, and the next development version is set with "bump2version patch".
test_native_code_releases_the_gil failed on Windows with Python 3.10
("_transform: only 3 ticks in 33 ms"). The background thread slept
0.5 ms per iteration, but on Windows before Python 3.11 time.sleep()
lasts at least about 15.6 ms, so a short native call saw only a few
iterations.
The thread now yields with time.sleep(0), which releases the GIL without
waiting for a timer. The images are passed as contiguous float64 arrays:
for the non-contiguous views used before, NumPy copied the data inside
the call and released the GIL itself while copying, which let the thread
run even with an extension that holds the GIL (0.2.8: 12 iterations with
time.sleep(0)). Measured now: 1 iteration per call with the 0.2.8
extension, several hundred to several thousand with the GIL released; the
threshold is raised from 5 to 20. Checked with a time.sleep() emulating
the Windows granularity.
The exact job failed on GitHub for two of 43 cases, scaled rotation and rigid body on the 25 x 33 synthetic scene, by up to 7e-15. The native code is not the cause: the synthetic test images are computed with numpy.exp, whose last bit depends on the vectorized implementation that NumPy selects for the CPU. Changing single pixels of the inputs by one bit locally reproduces exactly these deviations, while all cases with the recorded pc12 stack were bit-identical on GitHub as well. The exact job now runs the pc12 cases (all transformation types and reference modes, n_frames, moving average). The synthetic cases keep running with tolerances in the test jobs and remain exact on the machine that generated the baseline. test_regression.py, docs/validation.rst and docs/release.rst explain the limitation.
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This release modernizes the package. Apart from the corrections listed below, results of registrations and transformations are unchanged: they are verified bit for bit against 0.2.8.
License
NOTICE.Added
register_stack(),transform_stack()andregister_transform_stack()acceptn_jobs(number of threads;-1uses all CPUs). The native code releases the GIL, so threads are used and no data are copied between processes. Parallel results are identical to sequential results for all reference modes, including"previous"(Parallel image registration #14, parallelize register/transform stack #17, releasing GIL before c function calls #33).transform_stack()andregister_transform_stack()acceptout: a preallocated array of another dtype (integer dtypes are rounded and clipped), anumpy.memmap, or the input itself for in-place operation (Very high memory usage with pystackreg #28)StackReg.transform_points()applies a transformation to point coordinates, also for the bilinear transformation (Coordinate Based Registration? #42)pystackreg.util.max_displacement()measures the amplitude of transformations, e.g. to detect implausible registration results (Limit transformation amplitude #41)transform_stack()acceptsverboseandprogress_callback;register_transform_stack()acceptssuppress_axis_warning.py.typed), support for free-threaded CPython builds.Changed
transform_stack()no longer create temporary copies of the whole stack.transform()is about three times faster (1.6 times for the bilinear transformation); it no longer computes image pyramids and gradients that only the registration needs. The speed ofregister()is unchanged.tqdm.auto(update usage of tqdm #11)ValueError,TypeErrororRuntimeErrorwith specific messages instead of a bareException.register()andregister_stack()with aValueError. Previously such images silently produced an identity transformation.ValueError. Previously these cases read out-of-bounds memory or crashed.moving_average> 1) of floating-point stacks is computed in double precision, so results for such stacks can differ in the last digits from 0.2.8. Integer stacks are unaffected.-ffp-contract=off: results no longer depend on whether the CPU architecture fuses multiply-add operations (affects arm64 builds in the last bits).pyproject.toml; development uses Ruff, mypy and pytest.Fixed
reference="previous"combined withmoving_average> 1 registered the first frame against the last frame of the stack, which shifted thewhole registered stack.
moving_average> 1 gave wrong results foraxisother than 0 (util.running_mean()ignored the axis when taking differences).register()leaked the three returned arrays (about 430 bytes).transform()with extreme matrices; conversions now follow the semantics of the Java original.get_matrix()before a registration raised an unrelatedTypeError.Removed