Skip to content

Unwrap seed refactor - #8142

Merged
stefanv merged 30 commits into
scikit-image:mainfrom
matthew-brett:unwrap-seed-refactor
May 14, 2026
Merged

stefanv merged 30 commits into
scikit-image:mainfrom
matthew-brett:unwrap-seed-refactor

Conversation

@matthew-brett

@matthew-brett matthew-brett commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

This is a continuation of #8099

It includes:

  • @michaelbratsch's fixes to random seeding
  • Port to using Numpy RNG for random number generation, for better thread-safety.
  • Use intptr_t for variables containing array sizes or indices.
  • Some variable renaming for clarity, and removal of a TODO cleared up by the variable renaming.
  • Refactor of common code in 2D and 3D .c files into a new unwrap_common.h header file.
  • Added back sentinel large initial value for pixels / voxels for which we cannot calculate unreliability scores. This is from the original code before inclusion in Scikit-image.

I used AI to automate some variable renaming - specifically in commit 0879160, renaming e.g. image_width to n_j and wrap_around_x to wrap_around_j, mutatis mutandis for 2 and 3D. Then I checked the diff.

michaelbratsch and others added 8 commits March 19, 2026 20:50
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
* origin/main: (34 commits)
  Suppress tifffile DeprecationWarning in test_plugin_deprecation_on_imread (scikit-image#8138)
  Move tests back to doc build
  Fill out .PHONY targets
  Apply suggestions from code review
  Remove unused imports (apply commit hooks)
  Improve inserted docstring note of `deprecated_func` (scikit-image#8095)
  address review
  Update doc/source/index.rst
  Refactor migration doctests and run as tests
  Port tests for `features.canny` to skimage2 (scikit-image#8126)
  Remove unnecessary `grid` directive
  Re-add reference to migration guide
  Replace NumPy global RNG use in tests with local seeded RNGs (scikit-image#8084)
  Disable tests using matplotlib on pyodide (scikit-image#8082)
  Test with pythonoptimize (scikit-image#8108)
  Add skimage2 porting decorator (scikit-image#8114)
  Drop 3.13t builds from cibuildwheel configuration (scikit-image#8127)
  Restore wording of AI policy (scikit-image#8123)
  Port feature.canny to skimage2 (scikit-image#8047)
  address greptile review
  ...
When input seed was 0, we did not set the seed.  However, by default,
the unseeded C `rand()` assumes a seed of 1.  We might not have reached
that state (perhaps `rand()` was always seeded somehow), but in any
case, we're always seeding now.
@matthew-brett

Copy link
Copy Markdown
Contributor Author

A quick and dirty benchmark suggests timing is about the same before and after the Numpy RNG refactor:

import numpy as np
from skimage import data, img_as_float, color, exposure
from skimage.restoration import unwrap_phase


# Load an image as a floating-point grayscale
image = color.rgb2gray(img_as_float(data.chelsea()))
# Scale the image to [0, 4*pi]
image = exposure.rescale_intensity(image, out_range=(0, 4 * np.pi))
# Create a phase-wrapped image in the interval [-pi, pi)
image_wrapped = np.angle(np.exp(1j * image))
# Perform phase unwrapping

%timeit unwrap_phase(image_wrapped)

@matthew-brett matthew-brett added the 🩹 type: Bug fix Fixes unexpected or incorrect behavior label May 4, 2026
@greptile-apps

greptile-apps Bot commented May 4, 2026

Copy link
Copy Markdown
Contributor

Reviews (1): Last reviewed commit: "Refactor to use Numpy RNG in C code" | Re-trigger Greptile

@greptile-apps

greptile-apps Bot commented May 4, 2026

Copy link
Copy Markdown
Contributor

Reviews (2): Last reviewed commit: "Make random seeding check less sensitive..." | Re-trigger Greptile

@matthew-brett

Copy link
Copy Markdown
Contributor Author

Hmm - Greptile does (I think) a correct analysis at #8142 (comment) - that the random numbers only survive for corner (always) and border (depending on wrap_around) values for the relevant axes. I think Greptile also missed the case where the voxel is masked.

I see the original code had pixel_pointer->reliability = 9999999 + rand()...

@geggo - I think this is your code? Do you have any insight into the reasoning behind the random initialization?

@matthew-brett

Copy link
Copy Markdown
Contributor Author

Here's a guess - that the rand() component provides a tie-breaker only. It's not important for this purpose that that rand() returns a 32-bit unsigned int - specifically. The original code used 9999999 + rand() to (9999999) push the boundary pixels outside the range of plausible reliability, so they are processed last, and the rand() part adds a tie-breaker component.

In any case, let's go back to returning unsigned 32-bit integers for the random values, pending better understanding.

@greptile-apps

greptile-apps Bot commented May 4, 2026

Copy link
Copy Markdown
Contributor

Reviews (3): Last reviewed commit: "Revert to using uint32 for initializatio..." | Re-trigger Greptile

@geggo

geggo commented May 4, 2026

Copy link
Copy Markdown
Contributor

Sorry, I have no deeper insight into the unwrapping code, I only provided the initial Python warapper. But I think the analysis of Matthew-brett is correct.

@greptile-apps

greptile-apps Bot commented May 4, 2026

Copy link
Copy Markdown
Contributor

Reviews (4): Last reviewed commit: "Rename variables x, y, z to k, j, i for ..." | Re-trigger Greptile

@matthew-brett

Copy link
Copy Markdown
Contributor Author

@geggo - thanks much for the reply, that is very helpful - I'll keep exploring, but it does look like my AI-inspired guess is about right.

@greptile-apps

greptile-apps Bot commented May 5, 2026

Copy link
Copy Markdown
Contributor

Reviews (5): Last reviewed commit: "Update unwrap code to use intptr_t" | Re-trigger Greptile

Comment thread src/skimage/restoration/_unwrap_2d.pyx Resolved
Comment thread src/skimage/restoration/_unwrap_3d.pyx Resolved
@matthew-brett
matthew-brett force-pushed the unwrap-seed-refactor branch from 3b3b80a to 03955f2 Compare May 5, 2026 11:26
@greptile-apps

greptile-apps Bot commented May 5, 2026

Copy link
Copy Markdown
Contributor

Reviews (6): Last reviewed commit: "Update unwrap code to use intptr_t" | Re-trigger Greptile

@matthew-brett

matthew-brett commented May 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Further analysis by Gemini asserts that the wrap function in #8142 is incorrect, in that it does not normalize differences greater than $3 \pi$ to be in the range $(-\pi, \pi]$. Gemin asserts that:

The range $(-\pi, \pi]$ is a mathematical requirement to map the physical reality of phase (where jumps are integer
multiples of $2\pi$) into the periodic representation used by the algorithm. If wrap does not constrain values to this range,
the algorithm is no longer performing phase unwrapping as defined by the LJMU/Itoh framework; it is performing an
ill-defined mathematical transformation.

The wrap function is currently:

// gamma function in the paper
double wrap(double pixel_value) {
  double wrapped_pixel_value;
  if (pixel_value > PI)
    wrapped_pixel_value = pixel_value - TWOPI;
  else if (pixel_value < -PI)
    wrapped_pixel_value = pixel_value + TWOPI;
  else
    wrapped_pixel_value = pixel_value;
  return wrapped_pixel_value;
}

but this will leave gaps greater than $2 \pi$ for differences greater than $4 \pi$.

From the paper, on the "gamma function":

where $\gamma((\cdot))$ is a simple unwrapping operation to remove any $2 \pi$ steps between two
consecutive pixels.

I wonder whether wrap should do an fmod(value, TWO_PI) operation?

// gamma function in the paper
double wrap(double pixel_value) {
  double wrapped_pixel_value;
  double mod_value = fmod(pixel_value, TWOPI);
  if (mod_value > PI)
    wrapped_pixel_value = mod_value - TWOPI;
  else if (mod_value < -PI)
    wrapped_pixel_value = mod_value + TWOPI;
  else
    wrapped_pixel_value = mod_value;
  return wrapped_pixel_value;
}

@matthew-brett
matthew-brett force-pushed the unwrap-seed-refactor branch from 03955f2 to e06b557 Compare May 5, 2026 12:01
@greptile-apps

greptile-apps Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

Comments Outside Diff (1)

  1. src/skimage/restoration/unwrap_2d_ljmu.c, line 49 (link)

    P1 params_t.no_of_edges not updated to intptr_t (inconsistent with 3D)

    The 3D counterpart (unwrap_3d_ljmu.c) correctly updated params_t.no_of_edges to intptr_t, but this 2D struct field is still int. Both horizontalEDGEs (line 477) and verticalEDGEs (line 529) write an intptr_t local back to params->no_of_edges, silently truncating for very large images. gatherPIXELs then reads the truncated int value into an intptr_t k (line 542), causing an incorrectly shortened processing loop on any 2D image with more than ~2 billion edges.

Reviews (7): Last reviewed commit: "Update unwrap code to use intptr_t" | Re-trigger Greptile

As discussed at meeting.
@matthew-brett

matthew-brett commented May 13, 2026 •

Copy link
Copy Markdown
Contributor Author

I've restored the "sentinel value" from the original code (before inclusion in scikit-image) - that forces all uninitialized pixels to high (un)reliability values before adding the random component. I think this is correct, as otherwise, very rarely, a low number from the 32-bit random number generation will indicate low-unreliability pixels in the borders, etc, which could disturb the unwrapping.

@matthew-brett

Copy link
Copy Markdown
Contributor Author

I've put an explanatory note in unwrap.py, and pointed to that note from the C-files. I think that addresses #8142 (comment) - and that this one is ready to go.

@greptile-apps

greptile-apps Bot commented May 13, 2026

Copy link
Copy Markdown
Contributor

Reviews (14): Last reviewed commit: "Add comments on reliability score" | Re-trigger Greptile

@matthew-brett

Copy link
Copy Markdown
Contributor Author

Oh, and I refactored the common stuff out of the 2D and 3D .c files, into unwrap_common.h.

@matthew-brett

Copy link
Copy Markdown
Contributor Author

From discussion with @stefanv - renamed reliability variables etc to unreliability.

@greptile-apps

greptile-apps Bot commented May 13, 2026

Copy link
Copy Markdown
Contributor

Reviews (15): Last reviewed commit: "Rename "reliability" to "unreliability"" | Re-trigger Greptile

@stefanv

stefanv commented May 13, 2026 •

Copy link
Copy Markdown
Member

The bitgenerator.lock was pretty convincing that this is safe, but I asked Gemini to double-check. It came back with some other minor observations:

  1. Observations and Minor Issues
  • 3D Parameter Naming (Confusing but correct): In _unwrap_3d.pyx, there is a naming mismatch between the cdef extern declaration and the actual C header.

    • The .pyx extern names the wrap-around args as i, j, k.
    • The .h file names them k, j, i (matching the sizes n_k, n_j, n_i).
    • While technically safe (C doesn't care about parameter names in declarations), it makes the code harder to read. However, the order of arguments passed in the call unwrap3D(..., shape[2], shape[1], shape[0], wrap_k, wrap_j, wrap_i) correctly matches the C implementation's expectations (mapping X to
      Width, Y to Height, etc.).
  • Memory Allocation Safety (C level): I noticed that both the old and new C code use calloc to allocate large structures (PIXELM, EDGE, extended_mask) but do not check if the return is NULL.

1 pixel = (PIXELM *)calloc(image_size, sizeof(PIXELM));
2 // ... no check for pixel == NULL ...
3 initialisePIXELs(..., pixel, ...); // Will segfault if calloc failed

For a 10,000 x 10,000 image, pixel allocation requires ~7.2GB of RAM. If this fails, the program will crash with a segmentation fault. While this was likely a pre-existing issue, it's worth noting as a "safety" gap in the underlying C code.

@stefanv stefanv left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, Matthew, looks good overall!

As per AI policy, please mention if any AI tools were used (e.g., in the renaming of image_width to n_j etc.)

Comment thread src/skimage/restoration/meson.build Resolved
Comment thread src/skimage/restoration/unwrap.py Resolved
Comment thread src/skimage/restoration/unwrap.py Resolved
Comment thread src/skimage/restoration/unwrap.py Resolved
Comment thread src/skimage/restoration/unwrap.py Resolved
Comment thread src/skimage/restoration/unwrap_common.h Resolved
#include <numpy/random/bitgen.h>

#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does NumPy / Cython or, otherwise, math.h not have a built-in pi?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe it is possible for M_PI to be undeclared even after #include <math.h> - https://langdev.stackexchange.com/questions/2075/what-obstacles-prevented-c-and-c-from-standardizing-π - hence the ifndef M_PI ...

)
)

# Check that `None` is also a valid seed value, and that, with a much

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the advantage of testing this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only, I suppose, that we can pass None as a value to the rng argument. Should we not test that?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is the default behavior, so I imagine it is covered somewhere. But maybe not.

From Gemini suggestions.
As suggested by a Gemini review.
@matthew-brett

Copy link
Copy Markdown
Contributor Author

The bitgenerator.lock was pretty convincing that this is safe, but I asked Gemini to double-check. It came back with some other minor observations:

  1. Observations and Minor Issues
  • 3D Parameter Naming (Confusing but correct): In _unwrap_3d.pyx, there is a naming mismatch between the cdef extern declaration and the actual C header.

    • The .pyx extern names the wrap-around args as i, j, k.
    • The .h file names them k, j, i (matching the sizes n_k, n_j, n_i).
    • While technically safe (C doesn't care about parameter names in declarations), it makes the code harder to read. However, the order of arguments passed in the call unwrap3D(..., shape[2], shape[1], shape[0], wrap_k, wrap_j, wrap_i) correctly matches the C implementation's expectations (mapping X to
      Width, Y to Height, etc.).

Done in : eba93c7

  • Memory Allocation Safety (C level): I noticed that both the old and new C code use calloc to allocate large structures (PIXELM, EDGE, extended_mask) but do not check if the return is NULL.

1 pixel = (PIXELM *)calloc(image_size, sizeof(PIXELM));
2 // ... no check for pixel == NULL ...
3 initialisePIXELs(..., pixel, ...); // Will segfault if calloc failed
For a 10,000 x 10,000 image, pixel allocation requires ~7.2GB of RAM. If this fails, the program will crash with a segmentation fault. While this was likely a pre-existing issue, it's worth noting as a "safety" gap in the underlying C code.

Done in 05d3e30

…o unwrap-seed-refactor

* matthew-brett/unwrap-seed-refactor:
  Rename "reliability" to "unreliability"
@greptile-apps

greptile-apps Bot commented May 14, 2026

Copy link
Copy Markdown
Contributor

Reviews (16): Last reviewed commit: "Merge remote-tracking branch 'matthew-br..." | Re-trigger Greptile

matthew-brett and others added 6 commits May 14, 2026 11:39
From Stefanv comment.
From StefanV suggestion.
…o unwrap-seed-refactor

* matthew-brett/unwrap-seed-refactor:
  Update src/skimage/restoration/unwrap.py
  Update src/skimage/restoration/unwrap.py
@matthew-brett

Copy link
Copy Markdown
Contributor Author

Final call for changes. A couple of vaguely outstanding questions remain. But could live with the current state.

@greptile-apps

greptile-apps Bot commented May 14, 2026

Copy link
Copy Markdown
Contributor

Reviews (17): Last reviewed commit: "Merge remote-tracking branch 'matthew-br..." | Re-trigger Greptile

@stefanv
stefanv merged commit f024821 into scikit-image:main May 14, 2026
27 checks passed
@stefanv

stefanv commented May 14, 2026

Copy link
Copy Markdown
Member

Thanks very much!

@stefanv stefanv added this to the 0.27 milestone May 14, 2026
matthew-brett added a commit that referenced this pull request May 19, 2026
* origin/main:
  Use standard C99 static inline instead of `__inline` (#8159)
  Fix structural_similarity win_size / gaussian_weights conflict (#8162)
  Unwrap seed refactor (#8142)
  ci: Remove llvm build and add ccache support on windows (#8164)
  Document warn_external in contributing guide (#8163)
  CI: Fix emscripten dependencies and clean up wheel test commands (#8147)
  Test only changed subpackages (#8103)
  Fix nightlies: update deprecated scipy call, fix underdetermined test
  Fix minkowski distanced invocation for SciPy >= 1.18 (#8157)
  Port `structural_similarly` to ski2 (#8104)
  make spin build requirement a lower bound (#8158)
matthew-brett added a commit to matthew-brett/scikit-image that referenced this pull request May 21, 2026
* origin/main: (254 commits)
  Refactor, document migration utilities (scikit-image#8184)
  ci: improve handling of pr labels (scikit-image#8169)
  Doctest migration in PRs & on all platforms (scikit-image#8141)
  Update SKIP 4 (import hierarchy, backporting, testing) (scikit-image#8097)
  One page per function / class in HTML docs for skimage2 (scikit-image#8154)
  Pin minimum pytest to 9 (scikit-image#8174)
  docs: make source install instructions more discoverable and add build requirements to top level requirements file (scikit-image#8165)
  Drop `--maxfail=5` from local pytest config (scikit-image#8170)
  Use standard C99 static inline instead of `__inline` (scikit-image#8159)
  Fix structural_similarity win_size / gaussian_weights conflict (scikit-image#8162)
  Unwrap seed refactor (scikit-image#8142)
  ci: Remove llvm build and add ccache support on windows (scikit-image#8164)
  Document warn_external in contributing guide (scikit-image#8163)
  CI: Fix emscripten dependencies and clean up wheel test commands (scikit-image#8147)
  Test only changed subpackages (scikit-image#8103)
  Fix nightlies: update deprecated scipy call, fix underdetermined test
  Fix minkowski distanced invocation for SciPy >= 1.18 (scikit-image#8157)
  Port `structural_similarly` to ski2 (scikit-image#8104)
  make spin build requirement a lower bound (scikit-image#8158)
  Drop Python 3.11 Support (scikit-image#8153)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🩹 type: Bug fix Fixes unexpected or incorrect behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants