Skip to content

Replace NumPy global RNG use in tests with local seeded RNGs - #8084

Merged
stefanv merged 15 commits into
scikit-image:mainfrom
ngoldbaum:local-rng
Apr 25, 2026
Merged

stefanv merged 15 commits into
scikit-image:mainfrom
ngoldbaum:local-rng

Conversation

@ngoldbaum

Copy link
Copy Markdown
Contributor

Description

Updates the test suite to prefer explicitly seeded RNGs local to each test.

I'm using np.random.RandomState instead of np.random.default_rng because RandomState has stronger backward compatibility guarantees, which makes it more suitable for long-term use in a test suite.

There were a few cases where I found tests would only pass with specific seeds or RNG streams, and I left comments for those cases.

See https://github.com/numpy/numpy/pull/29729/changes where we did a similar change for NumPy.

Checklist

Release note

For maintainers and optionally contributors, please refer to the instructions on how to document this PR for the release notes.

The scikit-image test suite was updated to avoid using the global NumPy RNG. This makes it safe to run multiple tests simultaneously without any cross-talk.

@coderabbitai

coderabbitai Bot commented Mar 9, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Replaces non-deterministic/global NumPy RNG usage in many tests with local, fixed-seed np.random.RandomState instances and adds CONTRIBUTING.rst guidance recommending seeded local RNGs. A few tests had signatures updated to accept seeds; no production code/API changes.

Changes

Cohort / File(s) Summary
Documentation
CONTRIBUTING.rst
Adds guidance for tests to prefer local, seeded np.random.RandomState (examples for generating seeds and initializing rng) and notes about when seeds affect test outcomes.
Tests — global sweep
tests/... (many files under tests/)
Systematic replacement of global/default RNG usage with per-test np.random.RandomState(seed); calls like np.random.rand/.randn/.random/.integers/.choice replaced with rng.* to make test inputs deterministic.
Param/signature changes
tests/skimage/filters/test_median.py, tests/skimage/filters/test_unsharp_mask.py, tests/skimage/io/test_tifffile.py, tests/skimage/graph/test_mcp.py
Updated pytest parameterizations and function signatures to add seed parameters (and updated call sites). Reviewers should check pytest ordering and fixtures.
I/O & TIFF
tests/skimage/io/..., tests/skimage/io/test_tifffile.py
Removed module/global np.random.seed(...), added per-shape seeds in parametrization, and switched test image generation to rng.rand from np.random.rand.
Transform & Geometric tests
tests/skimage/transform/..., tests/skimage/transform/test_geometric.py
Introduced module/local RandomState constants (e.g., MODULE_RNG) and replaced ad-hoc RNGs with seeded RandomState instances for matrices, points, angles, and noise.
Filters, Morphology & Restoration
tests/skimage/filters/..., tests/skimage/morphology/..., tests/skimage/restoration/...
Per-test seeded RNGs introduced; some tests now reuse a single RNG within the test. Check consistency where multiple tests previously relied on shared global RNG state.
Feature / Descriptors / Metrics / Registration
tests/skimage/feature/..., tests/skimage/metrics/..., tests/skimage/registration/...
Deterministic data/noise generation via RandomState(seed) replacing default_rng/global seeds across many feature and metric tests.
Segmentation & Watershed
tests/skimage/segmentation/...
Switched random input generation to RandomState(seed); minor comments added about seed dependence.
Utilities & Shared tests
tests/skimage/util/..., tests/skimage/_shared/...
Replaced random calls with seeded RandomState and adjusted .integers→.randint and .choice usage where needed.
Minor production tweak
src/skimage/feature/_fisher_vector.py
Safer access to covariance_type via get on gm_args (no API change).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

type: Maintenance

Suggested reviewers

  • stefanv
  • matthew-brett
  • jni
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.87% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: replacing global RNG usage in tests with local seeded RNGs.
Description check ✅ Passed The description is directly related to the changeset, explaining the rationale for using RandomState over default_rng and mentioning specific test seed requirements.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 8

🧹 Nitpick comments (5)
tests/skimage/transform/test_geometric.py (1)

1015-1015: Rename the unused loop indices to _.

i is never read in either loop, so Ruff B007 will keep flagging these blocks.

Also applies to: 1077-1077

tests/skimage/feature/test_corner.py (1)

642-645: Rename the unused loop counter to _.

The loop variable on line 644 is declared but never referenced in the loop body. Using _ makes the intent explicit and prevents linter warnings.

Suggested diff
-    for i in range(20):
+    for _ in range(20):
         n = rng.randint(1, 21)
         results = peak_local_max(
             img_corners, min_distance=10, threshold_rel=0, num_peaks=n
         )
tests/skimage/registration/test_ilk.py (2)

119-124: Drop the unused tuple assignments inside pytest.raises.

These calls are only here for the exception side effect, and u, v = is what Ruff is warning about in this touched code.

♻️ Suggested cleanup
 def test_incompatible_shapes():
     rng = np.random.RandomState(811850096)
     I0 = rng.randn(256, 256)
     I1 = rng.randn(255, 256)
     with pytest.raises(ValueError):
-        u, v = optical_flow_ilk(I0, I1)
+        optical_flow_ilk(I0, I1)
 
 def test_wrong_dtype():
     rng = np.random.RandomState(87830699)
     img = rng.randn(256, 256)
     with pytest.raises(ValueError):
-        u, v = optical_flow_ilk(img, img, dtype='int')
+        optical_flow_ilk(img, img, dtype='int')

Also applies to: 127-131


67-69: Use RandomState here for consistency with other touched tests in this file.

All other modified tests in test_ilk.py use np.random.RandomState (lines 43, 81, 90, 100, 120, 128), but this test uses np.random.default_rng. Since the usage is straightforward (only rng.normal()), switching to RandomState would align with the PR's apparent standardization on that RNG API for long-term stable test data. If Generator is necessary here, document that rationale.

tests/skimage/registration/test_tvl1.py (1)

107-112: Drop the unused tuple assignments inside pytest.raises.

The assignments are not used, and the exception assertion works the same without them.

♻️ Suggested cleanup
 def test_incompatible_shapes():
     rng = np.random.RandomState(4152361355)
     I0 = rng.randn(256, 256)
     I1 = rng.randn(128, 256)
     with pytest.raises(ValueError):
-        u, v = optical_flow_tvl1(I0, I1)
+        optical_flow_tvl1(I0, I1)
 
 def test_wrong_dtype():
     rng = np.random.RandomState(740440569)
     img = rng.randn(256, 256)
     with pytest.raises(ValueError):
-        u, v = optical_flow_tvl1(img, img, dtype=np.int64)
+        optical_flow_tvl1(img, img, dtype=np.int64)

Also applies to: 115-119


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2b331534-9889-4a32-8a06-5e8dd39b400d

📥 Commits

Reviewing files that changed from the base of the PR and between 862aaf6 and 28aa9d2.

📒 Files selected for processing (61)
  • CONTRIBUTING.rst
  • tests/skimage/_shared/test_coord.py
  • tests/skimage/color/test_colorconv.py
  • tests/skimage/color/test_colorlabel.py
  • tests/skimage/exposure/test_exposure.py
  • tests/skimage/feature/test_basic_features.py
  • tests/skimage/feature/test_brief.py
  • tests/skimage/feature/test_canny.py
  • tests/skimage/feature/test_censure.py
  • tests/skimage/feature/test_corner.py
  • tests/skimage/feature/test_fisher_vector.py
  • tests/skimage/feature/test_peak.py
  • tests/skimage/feature/test_template.py
  • tests/skimage/feature/test_texture.py
  • tests/skimage/feature/test_util.py
  • tests/skimage/filters/rank/test_rank.py
  • tests/skimage/filters/test_edges.py
  • tests/skimage/filters/test_fft_based.py
  • tests/skimage/filters/test_gaussian.py
  • tests/skimage/filters/test_median.py
  • tests/skimage/filters/test_thresholding.py
  • tests/skimage/filters/test_unsharp_mask.py
  • tests/skimage/future/test_trainable_segmentation.py
  • tests/skimage/graph/test_mcp.py
  • tests/skimage/graph/test_pixel_graph.py
  • tests/skimage/io/test_imread.py
  • tests/skimage/io/test_pil.py
  • tests/skimage/io/test_tifffile.py
  • tests/skimage/measure/test_ccomp.py
  • tests/skimage/measure/test_find_contours.py
  • tests/skimage/measure/test_fit.py
  • tests/skimage/measure/test_moments.py
  • tests/skimage/metrics/test_simple_metrics.py
  • tests/skimage/metrics/test_structural_similarity.py
  • tests/skimage/morphology/test_flood_fill.py
  • tests/skimage/morphology/test_misc.py
  • tests/skimage/morphology/test_skeletonize.py
  • tests/skimage/registration/test_ilk.py
  • tests/skimage/registration/test_masked_phase_cross_correlation.py
  • tests/skimage/registration/test_tvl1.py
  • tests/skimage/restoration/test_denoise.py
  • tests/skimage/restoration/test_inpaint.py
  • tests/skimage/restoration/test_j_invariant.py
  • tests/skimage/restoration/test_restoration.py
  • tests/skimage/segmentation/test_boundaries.py
  • tests/skimage/segmentation/test_chan_vese.py
  • tests/skimage/segmentation/test_quickshift.py
  • tests/skimage/segmentation/test_random_walker.py
  • tests/skimage/segmentation/test_slic.py
  • tests/skimage/segmentation/test_watershed.py
  • tests/skimage/transform/test_geometric.py
  • tests/skimage/transform/test_hough_transform.py
  • tests/skimage/transform/test_integral.py
  • tests/skimage/transform/test_pyramids.py
  • tests/skimage/transform/test_radon_transform.py
  • tests/skimage/transform/test_warps.py
  • tests/skimage/util/test_dtype.py
  • tests/skimage/util/test_map_array.py
  • tests/skimage/util/test_montage.py
  • tests/skimage/util/test_random_noise.py
  • tests/skimage/util/test_slice_along_axes.py

Comment thread CONTRIBUTING.rst Resolved
Comment thread tests/skimage/filters/rank/test_rank.py Resolved
Comment thread tests/skimage/filters/test_median.py Resolved
Comment thread tests/skimage/graph/test_mcp.py Resolved
Comment on lines +37 to 38
# test result depends on this seed and RNG
rng = np.random.default_rng(583428449)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify whether this file still mixes Generator- and RandomState-based RNGs.
rg -n 'np\.random\.(default_rng|RandomState)\(' tests/skimage/segmentation/test_quickshift.py

Repository: scikit-image/scikit-image

Length of output: 161


Use RandomState here as well.

Line 38 uses np.random.default_rng while other tests in this file use np.random.RandomState, creating an inconsistency that conflicts with the suite-wide switch to standardize RNG usage.

Suggested diff
-    rng = np.random.default_rng(583428449)
+    rng = np.random.RandomState(583428449)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# test result depends on this seed and RNG
rng = np.random.default_rng(583428449)
# test result depends on this seed and RNG
rng = np.random.RandomState(583428449)

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.

Valid comment?

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.

Per the comment I added this line, the test result depends on this exact seed and RNG stream, so I can't change it.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 72843a89-828d-4e5a-8145-7f1d65ac2267

📥 Commits

Reviewing files that changed from the base of the PR and between 28aa9d2 and 1fe48a9.

📒 Files selected for processing (5)
  • tests/skimage/feature/test_fisher_vector.py
  • tests/skimage/filters/test_edges.py
  • tests/skimage/filters/test_thresholding.py
  • tests/skimage/filters/test_unsharp_mask.py
  • tests/skimage/graph/test_mcp.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/skimage/filters/test_thresholding.py
  • tests/skimage/filters/test_edges.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (4)
tests/skimage/measure/test_fit.py (4)

741-743: Prefix unused unpacked variable with underscore.

The rng variable is unpacked but never used since seed is now passed to ransac(). Per Python convention and static analysis hints, prefix it with _.

Suggested fix
 def test_ransac_geometric(ransac_params):
-    src, dst, model0, outliers, rng, seed = ransac_params
+    src, dst, model0, outliers, _rng, seed = ransac_params
     # estimate parameters of corrupted data
     model_est, inliers = ransac((src, dst), AffineTransform, 2, 20, rng=seed)

752-778: Prefix unused unpacked variables with underscores.

Multiple unpacked variables (outliers, rng, inliers) are unused in this test function.

Suggested fix
 def test_custom_estimate_warning(ransac_params):
     # Test that custom estimate class raises warning.
-    src, dst, model0, outliers, rng, seed = ransac_params
+    src, dst, model0, _outliers, _rng, seed = ransac_params
     ...
     with pytest.warns(FutureWarning, match=msg) as record:
-        model_est, inliers = ransac((src, dst), C, 2, 20, rng=seed)
+        model_est, _inliers = ransac((src, dst), C, 2, 20, rng=seed)

797-833: Prefix unused unpacked variables with underscores.

In test_ransac_model_class_protocol and test_custom_from_estimate_classmethod, variables model0, outliers, and rng are unpacked but never used.

Suggested fix
 def test_ransac_model_class_protocol(ransac_params):
     # Test custom classes that don't match protocol.
-    src, dst, model0, outliers, rng, seed = ransac_params
+    src, dst, _model0, _outliers, _rng, seed = ransac_params
     ...

 def test_custom_from_estimate_classmethod(ransac_params):
     # Test assertion that custom class `from_estimate` is class method.
-    src, dst, model0, outliers, rng, seed = ransac_params
+    src, dst, _model0, _outliers, _rng, seed = ransac_params

1038-1047: Consider adding a seed to the ransac call for full determinism.

The ransac call doesn't specify an rng parameter. While the test uses all 100 samples (min_samples=100) which should make the result deterministic regardless, adding rng=<seed> would align with the PR's goal of avoiding global RNG state.

Suggested fix
         model, inliers = ransac(
             (src, dst),
             PolynomialTransform,
             min_samples=100,
             residual_threshold=1.0,
             max_trials=1000,
             model_kwargs={'order': order},
+            rng=1,
         )

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3a7bd9d2-2acd-4b37-b719-3763a21d5e00

📥 Commits

Reviewing files that changed from the base of the PR and between 1fe48a9 and 8ebd053.

📒 Files selected for processing (3)
  • tests/skimage/graph/test_mcp.py
  • tests/skimage/measure/test_fit.py
  • tests/skimage/util/test_random_noise.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/skimage/graph/test_mcp.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
tests/skimage/transform/test_geometric.py (2)

77-77: Keep this parametrized input self-contained.

MODULE_RNG is still shared mutable state at module scope. If another draw is added anywhere before this parametrized list, this ProjectiveTransform case silently changes during collection. A one-off seeded RNG at the use site, or a hard-coded generated matrix, keeps the seed attached to the test input.

♻️ Suggested change
-MODULE_RNG = np.random.RandomState(3122886800)
@@
-        ProjectiveTransform(matrix=MODULE_RNG.rand(3, 3)),
+        ProjectiveTransform(
+            matrix=np.random.RandomState(3122886800).rand(3, 3)
+        ),

Also applies to: 959-959


123-127: Avoid the degenerate zero-scale case here.

rng.randint(0, 20) can produce 0, which makes the similarity-transform branch singular and the recovered rotation/scale non-unique. The current seed may avoid it, but any extra RNG draw earlier in this test would shift the stream and make this case brittle.

♻️ Suggested change
-        scale = rng.randint(0, 20)
+        scale = rng.randint(1, 20)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 94b57e17-b898-4b36-84ae-f278b2019b19

📥 Commits

Reviewing files that changed from the base of the PR and between 8ebd053 and 669f8b1.

📒 Files selected for processing (11)
  • CONTRIBUTING.rst
  • src/skimage/feature/_fisher_vector.py
  • tests/skimage/feature/test_fisher_vector.py
  • tests/skimage/filters/rank/test_rank.py
  • tests/skimage/filters/test_median.py
  • tests/skimage/measure/test_fit.py
  • tests/skimage/metrics/test_simple_metrics.py
  • tests/skimage/metrics/test_structural_similarity.py
  • tests/skimage/registration/test_masked_phase_cross_correlation.py
  • tests/skimage/transform/test_geometric.py
  • tests/skimage/transform/test_integral.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • tests/skimage/filters/rank/test_rank.py
  • tests/skimage/registration/test_masked_phase_cross_correlation.py
  • tests/skimage/metrics/test_simple_metrics.py

Comment thread tests/skimage/measure/test_fit.py Outdated
Comment on lines 712 to 715
seed = 4201799844
model_est, inliers = ransac(data0, CircleModel, 3, 5, rng=seed)
ransac(data0, CircleModel, 3, 5, rng=seed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Assert the repeated ransac call instead of discarding it.

Line 714 looks like it is meant to validate deterministic behavior with the same seed, but the result is ignored, so the test never checks that property.

Suggested assertion
     seed = 4201799844
     model_est, inliers = ransac(data0, CircleModel, 3, 5, rng=seed)
-    ransac(data0, CircleModel, 3, 5, rng=seed)
+    model_est_2, inliers_2 = ransac(data0, CircleModel, 3, 5, rng=seed)
+    assert_almost_equal(model_est.center, model_est_2.center)
+    assert_almost_equal(model_est.radius, model_est_2.radius)
+    assert_array_equal(inliers, inliers_2)

As per coding guidelines, "All code should have tests covering all modifications in behavior".

Comment thread tests/skimage/measure/test_fit.py Resolved
@ngoldbaum

Copy link
Copy Markdown
Contributor Author

I think this is ready for a human reviewer now. Very aware this is a big diff. Let me know if there's anything I can do to ease reviewing. Happy to split this up into chunks if you'd prefer that.

@ngoldbaum ngoldbaum mentioned this pull request Mar 11, 2026
2 of 3 tasks
@ngoldbaum

Copy link
Copy Markdown
Contributor Author

@stefanv I tried showing up at the weekly meeting so I could ask about my PRs but it looks like I'm the only one here. I see this needs a rebase but before I do that I want to make sure that a change like this is OK.

Can I get some feedback on how I should proceed to help improve the testing situation for free-threaded Python in Scikit-Image?

@stefanv

stefanv commented Mar 31, 2026

Copy link
Copy Markdown
Member

@stefanv I tried showing up at the weekly meeting so I could ask about my PRs but it looks like I'm the only one here. I see this needs a rebase but before I do that I want to make sure that a change like this is OK.

Can I get some feedback on how I should proceed to help improve the testing situation for free-threaded Python in Scikit-Image?

Argh, so sorry about that Nathan; we had some scheduling difficulties with the team, and have been moving meetings around this week. We'll get the calendar back on track for next week.

I think local, vs global, seeds are totally fine. Although I'm not sure we need RandomState any more. Tests should pass with any seed, in theory. @lagru any thoughts on this?

@ngoldbaum

Copy link
Copy Markdown
Contributor Author

Although I'm not sure we need RandomState any more.

I'm using RandomState because that's the RNG stream that's guaranteed not to change in future NumPy versions. default_rng() might change.

If the tests don't care about the RNG stream possibly changing in the future, I could probably switch everything to using a seeded default_rng().

@stefanv

stefanv commented Mar 31, 2026

Copy link
Copy Markdown
Member

Ah, yes, that's true; can you imagine the chaos if we (NumPy) were to do that 😅

Totally fine the way you have it, OK to seed default_rng directly too (we'll deal with that disaster when it comes).

But, yes, unless @lagru has concerns I think fine to go ahead.

@greptile-apps

greptile-apps Bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

Reviews (1): Last reviewed commit: "Fix some more occurances that have cropp..." | Re-trigger Greptile

Comment thread tests/skimage/feature/test_brief.py Resolved
Comment thread tests/skimage/filters/rank/test_rank.py Resolved
Comment thread tests/skimage/graph/test_mcp.py Resolved
@greptile-apps

greptile-apps Bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

Reviews (2): Last reviewed commit: "delete unused constant" | Re-trigger Greptile

@ngoldbaum

Copy link
Copy Markdown
Contributor Author

@stefanv rebased and ready for review, I think.

@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, @ngoldbaum—this was a lot of work!

We can go ahead and merge once the merge conflict is sorted.

@lagru Do you mind looking at the places where I commented; we may have identified some minor test suite issues along the way.

Comment thread tests/skimage/measure/test_fit.py Outdated
ransac(data0, CircleModel, 3, 5, rng=1)
seed = 4201799844
model_est, inliers = ransac(data0, CircleModel, 3, 5, rng=seed)
ransac(data0, CircleModel, 3, 5, rng=seed)

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 are we doing here.

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.

Yeah, this is weird. I changed it so the two instances use different seeds.

Comment thread tests/skimage/measure/test_fit.py Resolved
for ndim in range(1, 5):
xsize = [
N,
] * 5

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.

Hrm, wonder if we meant to write * ndim here.

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.

Good point. I didn't notice it until you pointed it out, but ndim is unused in the loop body.

However, with the following change:

diff --git a/tests/skimage/metrics/test_structural_similarity.py b/tests/skimage/metrics/test_structural_similarity.py
index cb803fa31..5bb1959e7 100644
--- a/tests/skimage/metrics/test_structural_similarity.py
+++ b/tests/skimage/metrics/test_structural_similarity.py
@@ -150,7 +150,7 @@ def test_structural_similarity_nD(dtype):
     for ndim in range(1, 5):
         xsize = [
             N,
-        ] * 5
+        ] * ndim
         X = (rng.rand(*xsize) * 255).astype(dtype)
         Y = (rng.rand(*xsize) * 255).astype(dtype)

I see test failures:

FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[uint8] - assert np.float64(0.12033917126639686) < 0.05
FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[float32] - assert np.float64(0.12066029480774887) < 0.05
FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[float64] - assert np.float64(0.12066033348447812) < 0.05

🤷 leaving it as-is for now but probably worth following up to understand why this is written this way

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.

@greptile can you file an issue for this comment?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I wasn't able to create the issue automatically (permissions blocked). Here's the content ready to file:

Title: Investigate * 5 vs * ndim in test_structural_similarity_nD

Body:

In tests/skimage/metrics/test_structural_similarity.py, test_structural_similarity_nD constructs test arrays using * 5 instead of * ndim:

for ndim in range(1, 5):
    xsize = [N] * 5  # should this be `* ndim`?
    X = (rng.rand(*xsize) * 255).astype(dtype)
    Y = (rng.rand(*xsize) * 255).astype(dtype)

ndim is effectively unused — arrays are always 5-dimensional regardless of the loop variable.

Changing * 5 → * ndim causes failures:

FAILED test_structural_similarity_nD[uint8] - assert np.float64(0.12033917126639686) < 0.05
FAILED test_structural_similarity_nD[float32] - assert np.float64(0.12066029480774887) < 0.05
FAILED test_structural_similarity_nD[float64] - assert np.float64(0.12066033348447812) < 0.05

Questions:

  • Was * 5 intentional? If so, what does the ndim loop actually exercise?
  • If it should be * ndim, the < 0.05 threshold likely needs revisiting for lower-dimensional inputs.

Noted in PR #8084.

Labels: tests

Tip: You can customize Greptile's behavior for this repo with .greptile/rules and .greptile/config.

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.

@greptile OK perhaps that's not a feature you have; you do have the permissions: Read and write access to checks, code, commit statuses, issues, and pull requests

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.

OK filed the issue #8129

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The tool call was blocked by the local execution environment, not GitHub permissions — so unfortunately I still can't create the issue from here. The read/write permissions you're seeing are on the GitHub App side, but this bot's tool access is being restricted at the agent level.

Your best bet is to file it manually using the content from my previous comment. Apologies for the confusion!

precomputed result in 2d case.
"""

# fails with other seeds?

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.

With all other seeds?

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 added seed as a parameterized fixture and ran this test for every seed between 0 and 100. It looks like the tests with float dtypes fail for all seeds besides 0.

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.

Uh oh, that's probably not right. Restoration is quite sensitive, so maybe the test condition is too strict.

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.

@pytest.mark.parametrize('ndim', [1, 2, 3])
def test_richardson_lucy(ndim, test_root_dir):
psf = np.ones([5] * ndim, dtype=float) / 5**ndim
# fails with different seeds?

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.

Flagging this one too for @lagru

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.

It looks like this one fails for ndim=2 for all seeds besides zero.

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.

Comment on lines +37 to 38
# test result depends on this seed and RNG
rng = np.random.default_rng(583428449)

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.

Valid comment?

@lagru
lagru self-requested a review April 23, 2026 07:01
@greptile-apps

greptile-apps Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

Reviews (3): Last reviewed commit: "Merge branch 'main' into local-rng" | Re-trigger Greptile

@ngoldbaum ngoldbaum left a comment

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.

Responded to all your comments, thanks @stefanv! I'm happy to open a followup issue with details about the tests that sensitive to the RNG stream.

Comment thread tests/skimage/measure/test_fit.py Outdated
ransac(data0, CircleModel, 3, 5, rng=1)
seed = 4201799844
model_est, inliers = ransac(data0, CircleModel, 3, 5, rng=seed)
ransac(data0, CircleModel, 3, 5, rng=seed)

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.

Yeah, this is weird. I changed it so the two instances use different seeds.

for ndim in range(1, 5):
xsize = [
N,
] * 5

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.

Good point. I didn't notice it until you pointed it out, but ndim is unused in the loop body.

However, with the following change:

diff --git a/tests/skimage/metrics/test_structural_similarity.py b/tests/skimage/metrics/test_structural_similarity.py
index cb803fa31..5bb1959e7 100644
--- a/tests/skimage/metrics/test_structural_similarity.py
+++ b/tests/skimage/metrics/test_structural_similarity.py
@@ -150,7 +150,7 @@ def test_structural_similarity_nD(dtype):
     for ndim in range(1, 5):
         xsize = [
             N,
-        ] * 5
+        ] * ndim
         X = (rng.rand(*xsize) * 255).astype(dtype)
         Y = (rng.rand(*xsize) * 255).astype(dtype)

I see test failures:

FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[uint8] - assert np.float64(0.12033917126639686) < 0.05
FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[float32] - assert np.float64(0.12066029480774887) < 0.05
FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[float64] - assert np.float64(0.12066033348447812) < 0.05

🤷 leaving it as-is for now but probably worth following up to understand why this is written this way

precomputed result in 2d case.
"""

# fails with other seeds?

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 added seed as a parameterized fixture and ran this test for every seed between 0 and 100. It looks like the tests with float dtypes fail for all seeds besides 0.

@pytest.mark.parametrize('ndim', [1, 2, 3])
def test_richardson_lucy(ndim, test_root_dir):
psf = np.ones([5] * ndim, dtype=float) / 5**ndim
# fails with different seeds?

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.

It looks like this one fails for ndim=2 for all seeds besides zero.

Comment on lines +37 to 38
# test result depends on this seed and RNG
rng = np.random.default_rng(583428449)

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.

Per the comment I added this line, the test result depends on this exact seed and RNG stream, so I can't change it.

@greptile-apps

greptile-apps Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

Reviews (4): Last reviewed commit: "use different RNGs in test_ransac_shape" | Re-trigger Greptile

@greptile-apps

greptile-apps Bot commented Apr 25, 2026

Copy link
Copy Markdown
Contributor

Reviews (5): Last reviewed commit: "Merge branch 'main' into local-rng" | Re-trigger Greptile

@stefanv
stefanv merged commit 9b9ada3 into scikit-image:main Apr 25, 2026
22 checks passed
@stefanv stefanv added this to the 0.27 milestone Apr 25, 2026
@stefanv

stefanv commented Apr 25, 2026

Copy link
Copy Markdown
Member

That was a big one; thanks Nathan.

matthew-brett added a commit that referenced this pull request Apr 27, 2026
* origin/main:
  Port tests for `features.canny` to skimage2 (#8126)
  Replace NumPy global RNG use in tests with local seeded RNGs (#8084)
  Disable tests using matplotlib on pyodide (#8082)
  Test with pythonoptimize (#8108)
  Add skimage2 porting decorator (#8114)
  Drop 3.13t builds from cibuildwheel configuration (#8127)
  Restore wording of AI policy (#8123)
blink1073 added a commit to stefanv/scikit-image that referenced this pull request Sep 27, 2026
Replace the module-level NumPy global RNG state in the skimage2
structural similarity tests with per-test local RNGs so the tests can
run under pytest-run-parallel. Use np.random.RandomState (per the
pattern established in scikit-image#8084) to keep the reference values that
cam_noisy depends on stable.

Resolves the merge conflict in test_structural_similarity_dtype and
addresses the review on scikit-image#8196.
blink1073 added a commit to stefanv/scikit-image that referenced this pull request Sep 27, 2026
Replace the module-level NumPy global RNG state in the skimage2
structural similarity tests with per-test local RNGs so the tests can
run under pytest-run-parallel. Use np.random.RandomState (per the
pattern established in scikit-image#8084) to keep the reference values that
cam_noisy depends on stable.

Resolves the merge conflict in test_structural_similarity_dtype and
addresses the review on scikit-image#8196.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants