Skip to content

Refactor smoothn.py with scipy interpolate and NumPy fallbacks - #381

Merged
alexlib merged 5 commits into
masterfrom
fix/smoothn-scipy-refactor
Nov 14, 2026
Merged

alexlib merged 5 commits into
masterfrom
fix/smoothn-scipy-refactor

Conversation

@alexlib

@alexlib alexlib commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

Refactors smoothn.py to use scipy.interpolate and penalized splines, with NumPy fallbacks. Adds tests. Ruff clean.

Summary by Sourcery

Modernize scalar-field smoothing with SciPy spline support, resilient NumPy fallbacks, and broader validation of missing-data and robust-smoothing workflows.

New Features:

  • Add scipy.interpolate-based 1D and 2D smoothing with support for gaps, masked arrays, configurable weights, and robust outlier handling.
  • Expose a unified smoothing API that supports both spline and penalized DCT methods.

Bug Fixes:

  • Preserve masked-array behavior and handle missing or non-finite values more consistently during smoothing.
  • Provide NumPy and optimization fallbacks when optional SciPy functionality is unavailable.

Enhancements:

  • Modernize smoothn.py with typed APIs, generalized N-dimensional DCT processing, GCV smoothing selection, and robust weighting utilities.

Documentation:

  • Update project documentation to describe the new smoothing capabilities and OpenPIV licensing.

Tests:

  • Expand smoothing tests to cover spline smoothing, missing data, masked arrays, robust outlier rejection, and fallback behavior.

Chores:

  • Bump the package version to 0.26.2 and clean up the smoothing test suite for Ruff compliance.

Copilot AI balanced review requested due to automatic review settings November 14, 2026 16:23
@sourcery-ai

sourcery-ai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Expose the smoothing method option through smoothn, dispatch 1D and 2D spline requests with axis validation, and provide the smooth_field alias.

  • openpiv/smoothn.py L556-654, L889-890

Implementation

Add transform and optimization fallbacks, robust-weight helpers, and SciPy-based 1D and 2D smoothing with missing-data handling.

  • openpiv/smoothn.py L1-552

Refactor the DCT smoothing path for weights, GCV selection, convergence, and masked-array preservation.

  • openpiv/smoothn.py L681-721, L726-758, L794-866 (+8 small edits)

Configuration

Bump the project version to 0.26.2 alongside the smoothing refactor.

  • pyproject.toml L3

Documentation

Update the module overview and README to describe the new smoothing capabilities and licensing.

  • CLAUDE.md L39
  • README.md L193

Tests

Expand smoothing tests to cover interpolation, gaps, masks, robust outlier handling, and the spline API.

  • openpiv/test/test_smoothn.py L1-28, L337-346, L659-760 (+40 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@alexlib
alexlib force-pushed the fix/smoothn-scipy-refactor branch from 0f0f4ac to 62c022e Compare November 14, 2026 16:24
sourcery-ai[bot]
sourcery-ai Bot previously approved these changes Nov 14, 2026

@sourcery-ai sourcery-ai 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.

Sourcery assessment

Approved.

@sourcery-ai sourcery-ai 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.

Hey - I've found 15 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="README.md" line_range="193" />
<code_context>


-Copyright statement: `smoothn.py` is a Python version of `smoothn.m` originally created by D. Garcia [https://de.mathworks.com/matlabcentral/fileexchange/25634-smoothn], written by Prof. Lewis and available on Github [https://github.com/profLewis/geogg122/blob/master/Chapter5_Interpolation/python/smoothn.py]. We include a version of it in the `openpiv` folder for convenience and preservation. We are thankful to the original authors for releasing their work as an open source. OpenPIV license does not relate to this code. Please communicate with the authors regarding their license. 
+Smoothing: `smoothn.py` provides scalar field smoothing for velocity fields (1D, 2D, and N-D) with support for missing data (NaNs) and masked arrays using `scipy.interpolate` and robust penalized spline methods. It is covered under the OpenPIV GPL v3 license. Based on discretized smoothing principles from D. Garcia (2010).

 ## How to cite this work
</code_context>
<issue_to_address>
**Smoothing license is misrepresented**

The README now claims `smoothn.py` is covered by the OpenPIV GPL v3 license and removes the original author attribution; the CLAUDE.md change also removes the statement that it is not covered and points readers to the README for attribution. This contradicts the repository’s licensing guidance and leaves users with incorrect licensing and attribution information.

Restore the licensing and attribution information required by the repository guidance in the README and retain an accurate reference to it in CLAUDE.md.

Also at `CLAUDE.md:39`.
</issue_to_address>

### Comment 2
<location path="openpiv/smoothn.py" line_range="146" />
<code_context>
+    MAD = np.median(np.abs(r_val - med))
+    if MAD == 0:
+        MAD = np.mean(np.abs(r_val - med))
+    denom = 1.4826 * MAD * np.sqrt(max(1e-12, 1.0 - h))
+    u = np.abs(r / denom)
+    wstr = str(wstr).lower()
</code_context>
<issue_to_address>
**Flat fields collapse to zero**

When robust smoothing encounters equal valid residuals, `RobustWeights` divides by a zero denominator and converts the resulting NaN weights to zero; the next robust iteration has no effective observations and replaces the constant field with zeros.

Handle a zero residual scale by assigning nonzero robust weights to the valid observations.

Also at `openpiv/smoothn.py:147-148`, `openpiv/smoothn.py:437`, `openpiv/smoothn.py:522`.
</issue_to_address>

### Comment 3
<location path="openpiv/smoothn.py" line_range="316" />
<code_context>
+
+    def conv1d_axis(arr: np.ndarray, axis: int) -> np.ndarray:
+        return np.apply_along_axis(
+            lambda m: np.convolve(m, k1d, mode="same"), axis, arr
+        )
+
</code_context>
<issue_to_address>
**Short fields change shape**

When a spline fit falls back to convolution and an input dimension is shorter than the generated kernel, `np.convolve(..., mode="same")` returns the longer operand's length, so the 1D and 2D fallbacks expand short dimensions; callers receive wrongly shaped fields or hit broadcasting and mask-shape errors.

Make the convolution fallback crop or pad its results so each smoothed dimension retains the input length.

Also at `openpiv/smoothn.py:319`, `openpiv/smoothn.py:515-519`.
</issue_to_address>

### Comment 4
<location path="openpiv/smoothn.py" line_range="609-612" />
<code_context>
     """
-    is_masked = False
+    # If spline method is explicitly requested and dimension is 1D or 2D:
+    if method in ("spline", "scipy"):
+        y_arr = np.asarray(y)
+        if y_arr.ndim == 2:
+            return scipy_smooth2d(
+                y,
+                s=s,
</code_context>
<issue_to_address>
**Spline options are ignored**

When a caller selects `method="spline"` or `method="scipy"` and supplies `axis`, `sd`, `smoothOrder`, or `z0`, `smoothn` dispatches to the spline helpers without forwarding these options; the helpers therefore smooth the full field and ignore uncertainty weighting and other requested settings, so callers get a result that does not honor their arguments.

Forward and apply the supported options in the spline dispatch and helpers.

Also at `openpiv/smoothn.py:613`, `openpiv/smoothn.py:621`.
</issue_to_address>

### Comment 5
<location path="openpiv/smoothn.py" line_range="471-505" />
<code_context>
+        weights = np.asarray(W, dtype=float).copy()
</code_context>
<issue_to_address>
**Spline weights are squared**

When the spline method receives nonuniform weights, `scipy_smooth1d` and `scipy_smooth2d` pass objective weights directly as SciPy spline residual multipliers, so the fit applies their squares instead of the intended relative influence; the 1D path also makes the result depend on uniformly rescaling the weights.

Pass consistently normalized square-root objective weights to both SciPy spline helpers.

Also at `openpiv/smoothn.py:423-425`.
</issue_to_address>

### Comment 6
<location path="openpiv/smoothn.py" line_range="408" />
<code_context>
+        var_z = 1.0
+
+    if s is None:
+        s_val = 0.5
+    else:
+        s_val = float(s)
</code_context>
<issue_to_address>
**Default smoothing depends on scale**

When the spline method is used without specifying `s`, `scipy_smooth1d` and `scipy_smooth2d` use a fixed `s_val` of `0.5` even though the spline smoothing factor depends on residual magnitudes, so rescaling the same field changes the effective smoothing and callers get inconsistent results.

Use the documented data-dependent default for `s` in both spline helpers.

Also at `openpiv/smoothn.py:491-494`.
</issue_to_address>

### Comment 7
<location path="openpiv/smoothn.py" line_range="655" />
<code_context>
+        valid = valid & (~mask)
+
+    if W is not None:
+        if np.any(W < 0):
+            raise ValueError("smoothn:NegativeWeights", "Weights must all be >=0")
+        valid = valid & (W > 0)
</code_context>
<issue_to_address>
**List weights raise TypeError**

When a caller supplies `W` as a Python list, the weight validation compares `W` with zero before converting it to an array, so Python raises `TypeError` and smoothing fails.

Convert `W` to an array before comparing its values with zero.

Also at `openpiv/smoothn.py:377-378`, `openpiv/smoothn.py:468`.
</issue_to_address>

### Comment 8
<location path="openpiv/smoothn.py" line_range="671" />
<code_context>
-    # Smoothness parameter and weights
-    # if s != None:
-    #  s = []
+        return y, s, 0, 0
+
     if W is None:
</code_context>
<issue_to_address>
**Singleton returns invalid metadata**

When the input contains a single element and `s` is omitted, a one-element input returns the caller's `s` unchanged and scalar `0` for `Wtot`; with the default `s=None`, callers receive a nonnumeric smoothing parameter and a non-array weight result despite the documented return types.

Return a numeric smoothing parameter and a weight array with the input shape on the short-input path.
</issue_to_address>

### Comment 9
<location path="openpiv/smoothn.py" line_range="671" />
<code_context>
-    # Smoothness parameter and weights
-    # if s != None:
-    #  s = []
+        return y, s, 0, 0
+
     if W is None:
</code_context>
<issue_to_address>
**Singleton masked input loses mask**

When the DCT method receives a masked array with fewer than two elements, the masked-array branch converts `y` to a plain ndarray before this early return, which occurs before the later mask restoration. A singleton masked input therefore returns an unmasked ndarray instead of preserving the input mask.

Reapply the original mask on the early-return path before returning.
</issue_to_address>

### Comment 10
<location path="openpiv/smoothn.py" line_range="68-74" />
<code_context>
+
+
+def _numpy_dct(
+    x: np.ndarray, norm: str = "ortho", type: int = 2, axis: int = -1
+) -> np.ndarray:
+    """Pure-NumPy DCT-II (orthonormal) along specified axis."""
+    axis = axis % x.ndim
+    M = _dct_matrix(x.shape[axis])
+    return np.apply_along_axis(lambda row: M @ row, axis, x)
+
+
+def _numpy_idct(
</code_context>
<issue_to_address>
**DCT fallback ignores transform options**

When sciPy's DCT routines are unavailable and a caller requests a transform type or normalization other than type-II with `norm="ortho"`, `_numpy_dct` and `_numpy_idct` always apply orthonormal type-II transforms, so the public `dct` and `idct` wrappers return coefficients that do not match the requested options.

Implement the supported transform types and normalizations in the NumPy fallbacks, or reject unsupported options explicitly.

Also at `openpiv/smoothn.py:77-83`, `openpiv/smoothn.py:91`.
</issue_to_address>

### Comment 11
<location path="openpiv/smoothn.py" line_range="609" />
<code_context>
     """
-    is_masked = False
+    # If spline method is explicitly requested and dimension is 1D or 2D:
+    if method in ("spline", "scipy"):
+        y_arr = np.asarray(y)
+        if y_arr.ndim == 2:
</code_context>
<issue_to_address>
**Invalid method silently uses DCT**

When a caller passes a `method` value other than `"dct"`, `"spline"`, or `"scipy"`, `smoothn` skips the spline branches and falls through to DCT smoothing, so callers receive results from a different engine without an error.

Validate `method` and raise an error for unsupported values.
</issue_to_address>

### Comment 12
<location path="openpiv/smoothn.py" line_range="414" />
<code_context>
+
+    Wtot = weights.copy()
+    z_smooth = None
+    exitflag = 1
+
+    kx = min(kx, len(np.unique(r_val)) - 1)
</code_context>
<issue_to_address>
**Nonconverged fits report success**

When robust spline iterations reach `max_iter` without converging, the spline helpers initialize `exitflag` to `1` and never update it based on convergence or iteration exhaustion, so callers receive a success status for a nonconverged fit.

Track robust-weight convergence and set `exitflag` to indicate when the iteration limit is reached without convergence.

Also at `openpiv/smoothn.py:415`, `openpiv/smoothn.py:498-499`.
</issue_to_address>

### Comment 13
<location path="openpiv/test/test_smoothn.py" line_range="727-729" />
<code_context>
+    z_true = np.sin(2 * np.pi * x)
+    z_noisy = z_true + np.random.normal(0, 0.05, z_true.shape)
+
+    z_smooth, _, exitflag, _ = smooth_field(z_noisy, s=0.5, method="spline")
+    assert exitflag == 1
+    assert np.mean((z_smooth - z_true) ** 2) < np.mean((z_noisy - z_true) ** 2)
+
+
</code_context>
<issue_to_address>
**Spline mode can go unchecked**

When the `method="spline"` dispatch is ignored and the input is smoothed by the default DCT path, in `test_smooth_field_spline_method`, the call at line 727 is checked only for an improved MSE at line 729; ordinary DCT smoothing can also satisfy that assertion, so ignoring the requested spline mode passes.

Assert that the spline implementation is selected, for example by replacing it with a test double and checking that it is called.
</issue_to_address>

### Comment 14
<location path="openpiv/test/test_smoothn.py" line_range="77" />
<code_context>

     # Apply smoothn with specified s
     s_value = 1.0
-    y_smooth, s, exitflag, Wtot = smoothn(y_noisy, s=s_value)
+    _y_smooth, s, _exitflag, _Wtot = smoothn(y_noisy, s=s_value)
</code_context>
<issue_to_address>
**No-op smoothing passes**

When `smoothn` returns the requested `s` but leaves the input unchanged, in `test_smoothn_with_s`, line 78 discards the smoothed array and line 81 checks only the returned parameter; an implementation that leaves the input unchanged but echoes `s` passes.

Assert a meaningful property of the returned smoothed array, such as reduced error against the known signal.
</issue_to_address>

### Comment 15
<location path="openpiv/smoothn.py" line_range="504" />
<code_context>
+        z_smooth = None
+        if HAS_SCIPY_INTERPOLATE and k >= 1 and nof > k + 1:
+            try:
+                spline = UnivariateSpline(x_val, z_val, w=w_val, s=s_val, k=k)
+                z_smooth = spline(x)
+            except Exception:  # noqa: BLE001
</code_context>
<issue_to_address>
**Weight scale changes 1D spline fit**

When A caller uses the 1D spline method with weights whose overall scale differs, `scipy_smooth1d` passes the raw weights to `UnivariateSpline`, so multiplying every weight by a constant changes the fit for a fixed `s`. This differs from the 2D spline and DCT paths, which normalize weights, making equivalent 1D and 2D calls behave inconsistently.

Normalize 1D spline weights consistently with the 2D spline and DCT paths before fitting.
</issue_to_address>

Sourcery assessment

Approval pending. 15 findings to address first.

Blocking findings: README.md:193, openpiv/smoothn.py:146, openpiv/smoothn.py:316, openpiv/smoothn.py:612, openpiv/smoothn.py:505, and 10 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread README.md


Copyright statement: `smoothn.py` is a Python version of `smoothn.m` originally created by D. Garcia [https://de.mathworks.com/matlabcentral/fileexchange/25634-smoothn], written by Prof. Lewis and available on Github [https://github.com/profLewis/geogg122/blob/master/Chapter5_Interpolation/python/smoothn.py]. We include a version of it in the `openpiv` folder for convenience and preservation. We are thankful to the original authors for releasing their work as an open source. OpenPIV license does not relate to this code. Please communicate with the authors regarding their license.
Smoothing: `smoothn.py` provides scalar field smoothing for velocity fields (1D, 2D, and N-D) with support for missing data (NaNs) and masked arrays using `scipy.interpolate` and robust penalized spline methods. It is covered under the OpenPIV GPL v3 license. Based on discretized smoothing principles from D. Garcia (2010).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Smoothing license is misrepresented

The README now claims smoothn.py is covered by the OpenPIV GPL v3 license and removes the original author attribution; the CLAUDE.md change also removes the statement that it is not covered and points readers to the README for attribution. This contradicts the repository’s licensing guidance and leaves users with incorrect licensing and attribution information.

Restore the licensing and attribution information required by the repository guidance in the README and retain an accurate reference to it in CLAUDE.md.

Also at CLAUDE.md:39.

Prompt for AI agents
In `README.md` at line 193:

**Smoothing license is misrepresented**

The README now claims `smoothn.py` is covered by the OpenPIV GPL v3 license and removes the original author attribution; the CLAUDE.md change also removes the statement that it is not covered and points readers to the README for attribution. This contradicts the repository’s licensing guidance and leaves users with incorrect licensing and attribution information.

Restore the licensing and attribution information required by the repository guidance in the README and retain an accurate reference to it in CLAUDE.md.

Also at `CLAUDE.md:39`.

From CLAUDE.md L39:

- `smoothn.py` — robust spline smoothing; a Python port of `smoothn.m` (D. Garcia / Prof. Lewis) bundled for convenience — it is not covered by the OpenPIV license, see README for attribution.

Comment thread openpiv/smoothn.py Resolved
Comment thread openpiv/smoothn.py Resolved
Comment thread openpiv/smoothn.py
Comment on lines +609 to +612
if method in ("spline", "scipy"):
y_arr = np.asarray(y)
if y_arr.ndim == 2:
return scipy_smooth2d(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Spline options are ignored

When a caller selects method="spline" or method="scipy" and supplies axis, sd, smoothOrder, or z0, smoothn dispatches to the spline helpers without forwarding these options; the helpers therefore smooth the full field and ignore uncertainty weighting and other requested settings, so callers get a result that does not honor their arguments.

Forward and apply the supported options in the spline dispatch and helpers.

Also at openpiv/smoothn.py:613, openpiv/smoothn.py:621.

Prompt for AI agents
In `openpiv/smoothn.py` at lines 609-612:

**Spline options are ignored**

When a caller selects `method="spline"` or `method="scipy"` and supplies `axis`, `sd`, `smoothOrder`, or `z0`, `smoothn` dispatches to the spline helpers without forwarding these options; the helpers therefore smooth the full field and ignore uncertainty weighting and other requested settings, so callers get a result that does not honor their arguments.

Forward and apply the supported options in the spline dispatch and helpers.

Also at `openpiv/smoothn.py:613`, `openpiv/smoothn.py:621`.

Comment thread openpiv/smoothn.py Outdated
Comment on lines +471 to +505
weights = np.asarray(W, dtype=float).copy()
else:
weights = np.ones(y_arr.shape, dtype=float)

weights[~valid] = 0.0
nof = int(valid.sum())
if nof < 2:
z = y_arr.copy()
if is_masked:
z = ma.array(z, mask=mask)
return z, 0.0 if s is None else float(s), 0, weights

N = len(y_arr)
x = np.arange(N)
x_val = x[valid]
z_val = y_arr[valid]
w_val = weights[valid]

float(np.var(z_val)) if len(z_val) > 1 else 1.0
if s is None:
s_val = 0.5
else:
s_val = float(s)

k = min(k, nof - 1)
Wtot = weights.copy()
z_smooth = None
exitflag = 1

for step in range(max_iter if isrobust else 1):
z_smooth = None
if HAS_SCIPY_INTERPOLATE and k >= 1 and nof > k + 1:
try:
spline = UnivariateSpline(x_val, z_val, w=w_val, s=s_val, k=k)
z_smooth = spline(x)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Spline weights are squared

When the spline method receives nonuniform weights, scipy_smooth1d and scipy_smooth2d pass objective weights directly as SciPy spline residual multipliers, so the fit applies their squares instead of the intended relative influence; the 1D path also makes the result depend on uniformly rescaling the weights.

Pass consistently normalized square-root objective weights to both SciPy spline helpers.

Also at openpiv/smoothn.py:423-425.

Prompt for AI agents
In `openpiv/smoothn.py` at lines 471-505:

**Spline weights are squared**

When the spline method receives nonuniform weights, `scipy_smooth1d` and `scipy_smooth2d` pass objective weights directly as SciPy spline residual multipliers, so the fit applies their squares instead of the intended relative influence; the 1D path also makes the result depend on uniformly rescaling the weights.

Pass consistently normalized square-root objective weights to both SciPy spline helpers.

Also at `openpiv/smoothn.py:423-425`.

Comment thread openpiv/smoothn.py
"""
is_masked = False
# If spline method is explicitly requested and dimension is 1D or 2D:
if method in ("spline", "scipy"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Invalid method silently uses DCT

When a caller passes a method value other than "dct", "spline", or "scipy", smoothn skips the spline branches and falls through to DCT smoothing, so callers receive results from a different engine without an error.

Validate method and raise an error for unsupported values.

Prompt for AI agents
In `openpiv/smoothn.py` at line 609:

**Invalid method silently uses DCT**

When a caller passes a `method` value other than `"dct"`, `"spline"`, or `"scipy"`, `smoothn` skips the spline branches and falls through to DCT smoothing, so callers receive results from a different engine without an error.

Validate `method` and raise an error for unsupported values.

Comment thread openpiv/smoothn.py

Wtot = weights.copy()
z_smooth = None
exitflag = 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Nonconverged fits report success

When robust spline iterations reach max_iter without converging, the spline helpers initialize exitflag to 1 and never update it based on convergence or iteration exhaustion, so callers receive a success status for a nonconverged fit.

Track robust-weight convergence and set exitflag to indicate when the iteration limit is reached without convergence.

Also at openpiv/smoothn.py:415, openpiv/smoothn.py:498-499.

Prompt for AI agents
In `openpiv/smoothn.py` at line 414:

**Nonconverged fits report success**

When robust spline iterations reach `max_iter` without converging, the spline helpers initialize `exitflag` to `1` and never update it based on convergence or iteration exhaustion, so callers receive a success status for a nonconverged fit.

Track robust-weight convergence and set `exitflag` to indicate when the iteration limit is reached without convergence.

Also at `openpiv/smoothn.py:415`, `openpiv/smoothn.py:498-499`.

Comment on lines +727 to +729
z_smooth, _, exitflag, _ = smooth_field(z_noisy, s=0.5, method="spline")
assert exitflag == 1
assert np.mean((z_smooth - z_true) ** 2) < np.mean((z_noisy - z_true) ** 2)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Spline mode can go unchecked

When the method="spline" dispatch is ignored and the input is smoothed by the default DCT path, in test_smooth_field_spline_method, the call at line 727 is checked only for an improved MSE at line 729; ordinary DCT smoothing can also satisfy that assertion, so ignoring the requested spline mode passes.

Assert that the spline implementation is selected, for example by replacing it with a test double and checking that it is called.

Prompt for AI agents
In `openpiv/test/test_smoothn.py` at lines 727-729:

**Spline mode can go unchecked**

When the `method="spline"` dispatch is ignored and the input is smoothed by the default DCT path, in `test_smooth_field_spline_method`, the call at line 727 is checked only for an improved MSE at line 729; ordinary DCT smoothing can also satisfy that assertion, so ignoring the requested spline mode passes.

Assert that the spline implementation is selected, for example by replacing it with a test double and checking that it is called.

@@ -62,11 +75,12 @@ def test_smoothn_with_s():

# Apply smoothn with specified s
s_value = 1.0

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · No-op smoothing passes

When smoothn returns the requested s but leaves the input unchanged, in test_smoothn_with_s, line 78 discards the smoothed array and line 81 checks only the returned parameter; an implementation that leaves the input unchanged but echoes s passes.

Assert a meaningful property of the returned smoothed array, such as reduced error against the known signal.

Prompt for AI agents
In `openpiv/test/test_smoothn.py` at line 77:

**No-op smoothing passes**

When `smoothn` returns the requested `s` but leaves the input unchanged, in `test_smoothn_with_s`, line 78 discards the smoothed array and line 81 checks only the returned parameter; an implementation that leaves the input unchanged but echoes `s` passes.

Assert a meaningful property of the returned smoothed array, such as reduced error against the known signal.

Comment thread openpiv/smoothn.py
z_smooth = None
if HAS_SCIPY_INTERPOLATE and k >= 1 and nof > k + 1:
try:
spline = UnivariateSpline(x_val, z_val, w=w_val, s=s_val, k=k)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Weight scale changes 1D spline fit

When A caller uses the 1D spline method with weights whose overall scale differs, scipy_smooth1d passes the raw weights to UnivariateSpline, so multiplying every weight by a constant changes the fit for a fixed s. This differs from the 2D spline and DCT paths, which normalize weights, making equivalent 1D and 2D calls behave inconsistently.

Normalize 1D spline weights consistently with the 2D spline and DCT paths before fitting.

Prompt for AI agents
In `openpiv/smoothn.py` at line 504:

**Weight scale changes 1D spline fit**

When A caller uses the 1D spline method with weights whose overall scale differs, `scipy_smooth1d` passes the raw weights to `UnivariateSpline`, so multiplying every weight by a constant changes the fit for a fixed `s`. This differs from the 2D spline and DCT paths, which normalize weights, making equivalent 1D and 2D calls behave inconsistently.

Normalize 1D spline weights consistently with the 2D spline and DCT paths before fitting.

Copilot AI 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.

🟡 Changes recommended

NumPy fallbacks can enlarge outputs and break residual or mask handling, while spline smoothing ignores measurement uncertainties and 2D axis restrictions.

3 open issues
What changed in this PR

Modernizes OpenPIV’s scalar-field smoothing for PIV velocity data, adding SciPy spline options alongside generalized N-D DCT smoothing.

Changes:

  • Adds 1D/2D spline smoothing, robust weighting, missing-data handling, and the smooth_field alias.
  • Introduces NumPy transform and optimization fallbacks, and expands tests for spline smoothing, gaps, masks, and outliers.
  • Updates smoothing documentation and the licensing statement.
File Description
README.md Describes smoothing capabilities and revises the licensing statement.
openpiv/​test/​test_smoothn.py Adds spline and public API tests; reformats existing tests.
openpiv/​smoothn.py Implements spline engines, NumPy fallbacks, and generalized DCT smoothing.
CLAUDE.md Updates the smoothing module’s architecture description.

Review effort: Balanced

Comment thread openpiv/smoothn.py Outdated

def conv1d_axis(arr: np.ndarray, axis: int) -> np.ndarray:
return np.apply_along_axis(
lambda m: np.convolve(m, k1d, mode="same"), axis, arr
Comment thread openpiv/smoothn.py
is_masked = False
# If spline method is explicitly requested and dimension is 1D or 2D:
if method in ("spline", "scipy"):
y_arr = np.asarray(y)
Comment thread openpiv/smoothn.py Resolved
@sourcery-ai
sourcery-ai Bot dismissed their stale review November 14, 2026 16:37

Sourcery withdrew this approval because the latest commits introduced blocking findings.

@alexlib alexlib left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

ready to merge

@alexlib
alexlib merged commit 99ecae3 into master Nov 14, 2026
32 of 34 checks passed
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