diff --git a/CLAUDE.md b/CLAUDE.md index 18b50e6d..15a01ac2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,7 @@ OpenPIV is a Python library for Particle Image Velocimetry (PIV) analysis of flu - `tools.py` — I/O and visualization: `imread()`, `save()`, `display_vector_field()`, `transform_coordinates()` (always call before saving/displaying results — raw PIV output coordinates are in image/array convention, not physical/plot convention). - `scaling.py` — coordinate scaling and transformation. - `preprocess.py` — image preprocessing (background subtraction, masking). -- `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. +- `smoothn.py` — robust scalar field smoothing using `scipy.interpolate` and penalized splines for 1D, 2D, and N-D data with missing values (NaNs) and masked arrays. - `phase_separation.py` — solid-phase / liquid-tracer separation utilities. ### Typical call chains diff --git a/README.md b/README.md index 7552b5f9..465073c3 100644 --- a/README.md +++ b/README.md @@ -190,7 +190,7 @@ These and many additional examples are in another repository: [OpenPIV-Python-Ex 15. [Yuri Ishizawa](https://github.com/yuriishizawa) -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 [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.593157.svg)](https://doi.org/10.5281/zenodo.593157) diff --git a/openpiv/smoothn.py b/openpiv/smoothn.py index 31be02d2..4d089168 100644 --- a/openpiv/smoothn.py +++ b/openpiv/smoothn.py @@ -1,788 +1,890 @@ +"""Robust and spline-based scalar field smoothing for OpenPIV. + +This module provides tools for smoothing scalar fields (such as PIV velocity +displacement fields u and v) containing measurement noise, missing values / gaps +(NaNs, infinities), and masked regions. + +Features: +- Bivariate / univariate spline smoothing powered by `scipy.interpolate` + (`SmoothBivariateSpline`, `UnivariateSpline`, `griddata`). +- Fast automated penalized discrete cosine transform (DCT) spline smoothing + with generalized cross-validation (GCV) parameter estimation. +- Iteratively re-weighted least squares (IRLS) robust smoothing for automatic + outlier rejection (bisquare, Cauchy, and Talworth weightings). +- Full support for `numpy.ma.MaskedArray`, preserving masks. +""" + +from typing import Any + import numpy as np -import numpy.ma as ma -from scipy.fftpack import dct, idct -from scipy.optimize import fmin_l_bfgs_b +from numpy import ma + +# Try importing modern scipy.fft, fall back to scipy.fftpack or pure-NumPy +try: + from scipy.fft import dct as _scipy_dct + from scipy.fft import idct as _scipy_idct +except ImportError: + try: + from scipy.fftpack import dct as _scipy_dct + from scipy.fftpack import idct as _scipy_idct + except ImportError: + _scipy_dct = None + _scipy_idct = None + +# Try importing scipy.optimize for GCV optimization +try: + from scipy.optimize import fmin_l_bfgs_b as _scipy_fmin_l_bfgs_b +except ImportError: + _scipy_fmin_l_bfgs_b = None + +# Try importing scipy.interpolate for modern spline smoothing +try: + from scipy.interpolate import ( + SmoothBivariateSpline, + UnivariateSpline, + ) + + HAS_SCIPY_INTERPOLATE = True +except ImportError: + HAS_SCIPY_INTERPOLATE = False + + +# --------------------------------------------------------------------------- +# Pure-NumPy DCT / IDCT Fallbacks +# --------------------------------------------------------------------------- + + +def _dct_matrix(N: int) -> np.ndarray: + """Generate orthogonal DCT-II transformation matrix of size N x N.""" + n = np.arange(N) + k = np.arange(N).reshape(-1, 1) + M = np.cos(np.pi * (2 * n + 1) * k / (2.0 * N)) + M[0, :] *= 1.0 / np.sqrt(2.0) + M *= np.sqrt(2.0 / N) + return M + + +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( + X: np.ndarray, norm: str = "ortho", type: int = 2, axis: int = -1 +) -> np.ndarray: + """Pure-NumPy IDCT-II (orthonormal) along specified axis.""" + axis = axis % X.ndim + M = _dct_matrix(X.shape[axis]) + return np.apply_along_axis(lambda row: M.T @ row, axis, X) + + +def dct( + x: np.ndarray, norm: str = "ortho", type: int = 2, axis: int = -1 +) -> np.ndarray: + """Discrete Cosine Transform (DCT-II). Uses scipy when available, NumPy fallback otherwise.""" + if _scipy_dct is not None: + return _scipy_dct(x, norm=norm, type=type, axis=axis) + return _numpy_dct(x, norm=norm, type=type, axis=axis) + + +def idct( + X: np.ndarray, norm: str = "ortho", type: int = 2, axis: int = -1 +) -> np.ndarray: + """Inverse Discrete Cosine Transform (IDCT-II). Uses scipy when available, NumPy fallback otherwise.""" + if _scipy_idct is not None: + return _scipy_idct(X, norm=norm, type=type, axis=axis) + return _numpy_idct(X, norm=norm, type=type, axis=axis) + + +def dctND(data: np.ndarray, f: Any = dct) -> np.ndarray: + """Multi-dimensional Discrete Cosine Transform or inverse transform.""" + data = np.asarray(data, dtype=float) + nd = data.ndim + res = data.copy() + for ax in range(nd): + res = f(res, norm="ortho", type=2, axis=ax) + return res + + +# --------------------------------------------------------------------------- +# Robust Weight Functions & Helper Utilities +# --------------------------------------------------------------------------- + + +def RobustWeights( + r: np.ndarray, I: np.ndarray, h: float, wstr: str = "bisquare" +) -> np.ndarray: + """Compute weights for robust smoothing from studentized residuals. + + Parameters + ---------- + r : ndarray + Residuals (y - z). + I : ndarray (bool) + Mask of valid / finite elements. + h : float + Leverage factor. + wstr : str, optional + Weight function type: 'bisquare' (default), 'cauchy', or 'talworth'. + + Returns + ------- + W : ndarray + Calculated robust weights in [0, 1]. + """ + r_val = r[I] + if len(r_val) == 0: + return np.ones_like(r) + med = np.median(r_val) + 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)) + if denom <= 0 or not np.isfinite(denom): + return np.ones_like(r) + u = np.abs(r / denom) + wstr = str(wstr).lower() + + if wstr == "cauchy": + c = 2.385 + W = 1.0 / (1.0 + (u / c) ** 2) + elif wstr == "talworth": + c = 2.795 + W = (u < c).astype(float) + else: # bisquare (Tukey biweight) + c = 4.685 + W = np.where(u < c, (1.0 - (u / c) ** 2) ** 2.0, 0.0) + + W = np.nan_to_num(W, nan=0.0) + return W + + +def InitialGuess(y: np.ndarray, z0: np.ndarray | None = None) -> np.ndarray: + """Compute or validate initial guess for smoothed array.""" + if z0 is not None and hasattr(z0, "shape") and z0.shape == y.shape: + return z0 + if isinstance(y, np.ma.MaskedArray): + return y.copy() + return y.copy() + + +def peaks(n: int | np.ndarray) -> np.ndarray | list[int]: + """Generate a 2D test surface with peaks or find 1D peak indices.""" + if isinstance(n, np.ndarray): + indices = [] + for i in range(1, len(n) - 1): + if n[i] > n[i - 1] and n[i] > n[i + 1]: + indices.append(i) + return indices + + xp = np.arange(n) + x, y = np.meshgrid(xp, xp) + z = np.zeros_like(x, dtype=float) + for _ in range(max(1, n // 5)): + x0 = np.random.random() * n + y0 = np.random.random() * n + sdx = np.random.random() * n / 4.0 + sdy = sdx + c = np.random.random() * 2.0 - 1.0 + f = np.exp( + -(((x - x0) / sdx) ** 2) + - ((y - y0) / sdy) ** 2 + - ((x - x0) / sdx) * ((y - y0) / sdy) * c + ) + f *= np.random.random() + z += f + return z + + +def warning(s1: str, s2: str | list[str] | tuple[str, ...]) -> None: + """Print or log a warning message.""" + print(s1) + if isinstance(s2, (list, tuple)): + print(s2[0]) + else: + print(s2) + + +def smooth(u: np.ndarray, mask: np.ndarray) -> None: + """Smooth a 2D array in-place while respecting a boolean exclusion mask.""" + m = ~mask + r = u * m + a = 4 * r[1:-1, 1:-1] + r[2:, 1:-1] + r[:-2, 1:-1] + r[1:-1, 2:] + r[1:-1, :-2] + b = 4 * m[1:-1, 1:-1] + m[2:, 1:-1] + m[:-2, 1:-1] + m[1:-1, 2:] + m[1:-1, :-2] + b[b == 0] = 1.0 + u[1:-1, 1:-1] = a / b + + +def smooth_masked_array(u: np.ma.MaskedArray) -> np.ma.MaskedArray: + """Smooth a MaskedArray using iterative neighbor averaging.""" + if not isinstance(u, np.ma.MaskedArray): + raise TypeError("Expected masked array") + m = u.mask.copy() if hasattr(u.mask, "copy") else u.mask + u_data = u.data.copy() + for _ in range(10): + smooth(u_data, m) + return np.ma.array(u_data, mask=m) + + +# --------------------------------------------------------------------------- +# GCV Function and 1D Optimization Fallback +# --------------------------------------------------------------------------- + + +def gcv( + p: float, + Lambda: np.ndarray, + aow: Any, + DCTy: np.ndarray, + IsFinite: np.ndarray, + Wtot: np.ndarray, + y: np.ndarray, + nof: int, + noe: int, + smoothOrder: float, +) -> float: + """Generalized Cross-Validation (GCV) score for DCT-based spline smoothing.""" + s = 10.0**p + Gamma = 1.0 / (1.0 + (s * np.abs(Lambda)) ** smoothOrder) + aow_arr = np.asarray(aow) + if np.all(aow_arr > 0.9): + RSS = np.linalg.norm(DCTy * (Gamma - 1.0)) ** 2 + else: + yhat = dctND(Gamma * DCTy, f=idct) + RSS = ( + np.linalg.norm(np.sqrt(Wtot[IsFinite]) * (y[IsFinite] - yhat[IsFinite])) + ** 2 + ) + TrH = np.sum(Gamma) + denom = 1.0 - TrH / float(noe) + if denom <= 0: + return 1e12 + GCVscore = RSS / float(nof) / (denom**2) + return float(GCVscore) + + +def _golden_section_search( + func: Any, a: float, b: float, tol: float = 0.05, args: tuple = () +) -> list[float]: + """1D Golden-section optimization fallback when scipy.optimize is not installed.""" + phi = (1.0 + np.sqrt(5.0)) / 2.0 + resphi = 2.0 - phi + x1 = a + resphi * (b - a) + x2 = b - resphi * (b - a) + f1 = func(x1, *args) + f2 = func(x2, *args) + + while abs(b - a) > tol: + if f1 < f2: + b = x2 + x2 = x1 + f2 = f1 + x1 = a + resphi * (b - a) + f1 = func(x1, *args) + else: + a = x1 + x1 = x2 + f1 = f2 + x2 = b - resphi * (b - a) + f2 = func(x2, *args) + + return [(a + b) / 2.0] + + +# --------------------------------------------------------------------------- +# scipy.interpolate Modern Smoothing Implementations +# --------------------------------------------------------------------------- + + +def _normalized_conv2d(y: np.ndarray, weights: np.ndarray, sigma: float) -> np.ndarray: + """Pure-NumPy normalized convolution for 2D smoothing over gaps.""" + sigma = max(0.5, float(sigma)) + radius = int(np.ceil(3.0 * sigma)) + ax = np.arange(-radius, radius + 1) + k1d = np.exp(-0.5 * (ax / sigma) ** 2) + k1d /= k1d.sum() + + w = np.asarray(weights, dtype=float) + valid = (w > 0) & np.isfinite(y) + w_clean = np.where(valid, w, 0.0) + data = np.where(valid, y, 0.0) + + def _conv_same(m: np.ndarray, kernel: np.ndarray) -> np.ndarray: + full = np.convolve(m, kernel, mode="full") + start = (full.shape[0] - m.shape[0]) // 2 + return full[start : start + m.shape[0]] + + def conv1d_axis(arr: np.ndarray, axis: int) -> np.ndarray: + return np.apply_along_axis(lambda m: _conv_same(m, k1d), axis, arr) + + smooth_data = conv1d_axis(conv1d_axis(data * w_clean, 0), 1) + smooth_w = conv1d_axis(conv1d_axis(w_clean, 0), 1) + return np.where(smooth_w > 1e-6, smooth_data / np.maximum(smooth_w, 1e-12), 0.0) + + +def scipy_smooth2d( + y: np.ndarray, + s: float | None = None, + W: np.ndarray | None = None, + isrobust: bool = False, + weightstr: str = "bisquare", + max_iter: int = 3, + kx: int = 3, + ky: int = 3, +) -> tuple[np.ndarray, float, int, np.ndarray]: + """Smooth a 2D scalar field (such as PIV displacement u or v) using scipy.interpolate. + + Handles missing values (NaNs, Infs, and masked elements) by fitting a + bivariate spline over valid grid locations, naturally filling gaps. + + Parameters + ---------- + y : array_like or MaskedArray + 2D scalar field to smooth. + s : float, optional + Smoothing parameter. Larger values produce smoother results. + If None, a default based on data size and variance is used. + W : array_like, optional + Weights array matching y.shape. Must be >= 0. + isrobust : bool, optional + If True, performs iterative robust reweighting to reject outliers. + weightstr : str, optional + Robust weight function ('bisquare', 'cauchy', 'talworth'). + max_iter : int, optional + Maximum iterations for robust smoothing. + kx, ky : int, optional + Degree of the bivariate spline (default 3, cubic). + + Returns + ------- + z : ndarray or MaskedArray + Smoothed array, with original mask preserved if input was masked. + s : float + Smoothing factor used. + exitflag : int + 1 if convergence was reached, 0 otherwise. + Wtot : ndarray + Final weighting array. + """ + is_masked = isinstance(y, ma.MaskedArray) + mask = y.mask.copy() if is_masked else None + y_arr = np.asarray(y, dtype=float) + + valid = np.isfinite(y_arr) + if is_masked: + 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) + 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 + + H, W_cols = y_arr.shape + rows, cols = np.mgrid[0:H, 0:W_cols] + r_val = rows[valid] + c_val = cols[valid] + z_val = y_arr[valid] + w_val = weights[valid] + + # Normalize weights + if w_val.max() > 0: + w_val = w_val / w_val.max() + + var_z = float(np.var(z_val)) if len(z_val) > 1 else 1.0 + if var_z == 0: + var_z = 1.0 + + if s is None: + s_val = 0.5 + else: + s_val = float(s) + + Wtot = weights.copy() + z_smooth = None + exitflag = 1 + + kx = min(kx, len(np.unique(r_val)) - 1) + ky = min(ky, len(np.unique(c_val)) - 1) + + for step in range(max_iter if isrobust else 1): + z_smooth = None + if HAS_SCIPY_INTERPOLATE and kx >= 1 and ky >= 1 and nof > (kx + 1) * (ky + 1): + try: + spline = SmoothBivariateSpline( + r_val, c_val, z_val, w=w_val, s=s_val, kx=kx, ky=ky + ) + _zs = spline(np.arange(H), np.arange(W_cols)) + if not np.all(np.isfinite(_zs)): + z_smooth = None + else: + z_smooth = _zs + except Exception: # noqa: BLE001 + z_smooth = None + + if z_smooth is None: + # Fallback using normalized convolution with robust weights + sigma = max(0.5, float(s if s is not None else 1.0)) + z_smooth = _normalized_conv2d(y_arr, Wtot, sigma) + + if isrobust and step < max_iter - 1: + r = y_arr - z_smooth + w_rob = RobustWeights(r, valid, 0.1, weightstr) + Wtot = weights * w_rob + w_val = Wtot[valid] + if w_val.max() > 0: + w_val = w_val / w_val.max() + + if is_masked: + z_smooth = ma.array(z_smooth, mask=mask) + + return z_smooth, float(s if s is not None else s_val), exitflag, Wtot + + +def scipy_smooth1d( + y: np.ndarray, + s: float | None = None, + W: np.ndarray | None = None, + isrobust: bool = False, + weightstr: str = "bisquare", + max_iter: int = 3, + k: int = 3, +) -> tuple[np.ndarray, float, int, np.ndarray]: + """Smooth a 1D scalar signal using scipy.interpolate.UnivariateSpline.""" + is_masked = isinstance(y, ma.MaskedArray) + mask = y.mask.copy() if is_masked else None + y_arr = np.asarray(y, dtype=float) + + valid = np.isfinite(y_arr) + if is_masked: + 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) + 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) + _zs = spline(x) + if not np.all(np.isfinite(_zs)): + z_smooth = None + else: + z_smooth = _zs + except Exception: # noqa: BLE001 + z_smooth = None + + if z_smooth is None: + sigma = max(0.5, float(s if s is not None else 1.0)) + radius = int(np.ceil(3.0 * sigma)) + ax = np.arange(-radius, radius + 1) + k1d = np.exp(-0.5 * (ax / sigma) ** 2) + k1d /= k1d.sum() + data = np.where(valid, y_arr, 0.0) + _sm_data_full = np.convolve(data * Wtot, k1d, mode="full") + _sm_w_full = np.convolve(Wtot, k1d, mode="full") + _start = (_sm_data_full.shape[0] - data.shape[0]) // 2 + sm_data = _sm_data_full[_start : _start + data.shape[0]] + sm_w = _sm_w_full[_start : _start + data.shape[0]] + z_smooth = np.where(sm_w > 1e-6, sm_data / np.maximum(sm_w, 1e-12), 0.0) + + if isrobust and step < max_iter - 1: + r = y_arr - z_smooth + w_rob = RobustWeights(r, valid, 0.1, weightstr) + Wtot = weights * w_rob + w_val = Wtot[valid] + if w_val.max() > 0: + w_val = w_val / w_val.max() + + if is_masked: + z_smooth = ma.array(z_smooth, mask=mask) + + return z_smooth, float(s if s is not None else s_val), exitflag, Wtot + + +# --------------------------------------------------------------------------- +# Penalized DCT Spline Smoothing (smoothn) +# --------------------------------------------------------------------------- def smoothn( - y, - nS0=10, - axis=None, - smoothOrder=2.0, - sd=None, - verbose=False, - s0=None, - z0=None, - isrobust=False, - W=None, - s=None, - MaxIter=100, - TolZ=1e-3, - weightstr="bisquare", -): + y: Any, + nS0: int = 10, + axis: int | tuple[int, ...] | None = None, + smoothOrder: float = 2.0, + sd: Any | None = None, + verbose: bool = False, + s0: float | None = None, + z0: Any | None = None, + isrobust: bool = False, + W: Any | None = None, + s: float | None = None, + MaxIter: int = 100, + TolZ: float = 1e-3, + weightstr: str = "bisquare", + method: str = "dct", +) -> tuple[np.ndarray, float, int, np.ndarray]: """Robust spline smoothing for 1-D to N-D data. - This function provides a fast, automated and robust discretized smoothing - spline for data of any dimension. It can handle missing values and supports - robust smoothing that minimizes the influence of outlying data. + This function provides automated and robust discretized smoothing + for data of any dimension, handling missing values (NaNs, Infs), + masked arrays, and outlying data. Parameters ---------- - y : array_like - The data to be smoothed. Can be any N-D noisy array (time series, - images, 3D data, etc.). Non-finite data (NaN or Inf) are treated - as missing values. + y : array_like or MaskedArray + The data to be smoothed (1D, 2D, 3D, or ND). nS0 : int, optional - Number of samples used when automatically determining the smoothing - parameter. Default is 10. + Number of samples used when automatically determining smoothing parameter. axis : int or tuple of ints, optional - Axis or axes along which the smoothing is performed. If None (default), + Axis or axes along which the smoothing is performed. If None, smoothing is performed along all axes. smoothOrder : float, optional - Order of the smoothing. Default is 2.0 (equivalent to cubic spline). + Order of the smoothing (default 2.0, equivalent to cubic spline). sd : array_like, optional - Standard deviation of the data. If provided, it is used to compute - weights as 1/sd^2. + Standard deviation array. If provided, weights are computed as 1/sd^2. verbose : bool, optional - If True, display progress information. Default is False. + If True, displays progress information with iterations and tolerance. s0 : float, optional - Initial value for the smoothing parameter. If None (default), it is - automatically determined. + Initial value for smoothing parameter. z0 : array_like, optional - Initial guess for the smoothed data. If None (default), the original - data is used. + Initial guess for the smoothed data. isrobust : bool, optional - If True, perform robust smoothing that minimizes the influence of - outlying data. Default is False. + If True, performs robust smoothing to suppress outliers. W : array_like, optional - Weighting array of positive values, must have the same size as y. - A zero weight corresponds to a missing value. + Weighting array of non-negative values matching y.shape. s : float, optional - Smoothing parameter. If None (default), it is automatically determined - using the generalized cross-validation (GCV) method. Larger values - produce smoother results. + Smoothing parameter. If None, determined via generalized cross-validation (GCV). MaxIter : int, optional - Maximum number of iterations allowed. Default is 100. + Maximum number of iterations allowed (default 100). TolZ : float, optional - Termination tolerance on Z. Must be between 0 and 1. Default is 1e-3. + Termination tolerance on relative change in Z (default 1e-3). weightstr : str, optional - Type of weight function for robust smoothing. Options are 'bisquare' - (default), 'cauchy', or 'talworth'. + Weight function for robust smoothing ('bisquare', 'cauchy', 'talworth'). + method : str, optional + Smoothing engine: 'dct' (penalized DCT spline, default) or 'spline' / 'scipy' + (scipy.interpolate B-spline). Returns ------- - z : ndarray - The smoothed array. + z : ndarray or MaskedArray + The smoothed array. Preserves MaskedArray if input was masked. s : float The smoothing parameter used. exitflag : int - Describes the exit condition: - 1 - Convergence was reached - 0 - Maximum number of iterations was reached - -1 - DCT/IDCT functions not available + 1 if convergence was reached, 0 if maximum iterations was exceeded. Wtot : ndarray - The final weighting array used for the smoothing. - - Notes - ----- - The function uses the discrete cosine transform (DCT) to efficiently - compute the smoothing. The smoothing parameter s is determined automatically - using the generalized cross-validation (GCV) method if not provided. - - For robust smoothing, an iteratively re-weighted process is used to - minimize the influence of outliers. - - Reference - --------- - Garcia D, Robust smoothing of gridded data in one and higher dimensions - with missing values. Computational Statistics & Data Analysis, 2010. + The final weighting array used for smoothing. """ - 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: + if axis is not None: + axes = np.atleast_1d(axis).ravel() + if ( + not np.all(np.isin(axes, (-2, -1, 0, 1))) + or set(axes % 2) != {0, 1} + ): + raise ValueError( + "The spline method requires smoothing along both axes; " + "use method='dct' for axis-restricted smoothing." + ) + return scipy_smooth2d( + y, + s=s, + W=W, + isrobust=isrobust, + weightstr=weightstr, + max_iter=min(3, MaxIter), + ) + elif y_arr.ndim == 1: + return scipy_smooth1d( + y, + s=s, + W=W, + isrobust=isrobust, + weightstr=weightstr, + max_iter=min(3, MaxIter), + ) - if type(y) == ma.MaskedArray: # masked array + is_masked = False + if isinstance(y, ma.MaskedArray): is_masked = True - mask = y.mask - y = np.array(y) - y[mask] = 0.0 - if W != None: - W = np.array(W) + mask = y.mask.copy() + y_arr = np.array(y, dtype=float) + y_arr[mask] = np.nan + if W is not None: + W = np.array(W, dtype=float) W[mask] = 0.0 - if sd != None: - W = np.array(1.0 / sd ** 2) + if sd is not None: + W = np.array(1.0 / np.array(sd) ** 2, dtype=float) W[mask] = 0.0 sd = None - y[mask] = np.nan + y = y_arr + else: + y = np.array(y, dtype=float) if sd is not None: - sd_ = np.array(sd) + sd_ = np.array(sd, dtype=float) mask = sd_ > 0.0 W = np.zeros_like(sd_) W[mask] = 1.0 / sd_[mask] ** 2 sd = None if W is not None: - W = W / np.max(W) + if np.any(W < 0): + raise ValueError("smoothn:NegativeWeights", "Weights must all be >=0") + max_W = np.max(W) + if max_W > 0: + W = W / max_W sizy = y.shape + if axis is None: + axis = tuple(range(y.ndim)) + elif isinstance(axis, int): + axis = (axis,) + else: + axis = tuple(np.array(axis).flatten()) - # sort axis - if axis == None: - axis = tuple(np.arange(y.ndim)) - - noe = y.size # number of elements + noe = y.size if noe < 2: - z = y - exitflag = 0 - Wtot = 0 - return z, s, exitflag, Wtot - # --- - # Smoothness parameter and weights - # if s != None: - # s = [] + return y, s, 0, 0 + if W is None: - W = np.ones(sizy) - - # if z0 == None: - # z0 = y.copy() - - # --- - # "Weighting function" criterion - weightstr = weightstr.lower() - # --- - # Weights. Zero weights are assigned to not finite values (Inf or NaN), - # (Inf/NaN values = missing data). - IsFinite = np.array(np.isfinite(y)).astype(bool) - nof = IsFinite.sum() # number of finite elements + W = np.ones(sizy, dtype=float) + + IsFinite = np.isfinite(y) + nof = IsFinite.sum() W = W * IsFinite - if np.any(W < 0): - raise ValueError("smoothn:NegativeWeights", "Weights must all be >=0") - else: - # W = W/np.max(W) - pass - # --- - # Weighted or missing data? + isweighted = np.any(W != 1) - # --- - # Robust smoothing? - # isrobust - # --- - # Automatic smoothing? - isauto = not s - # --- - # DCT and IDCT are required - # We already imported them at the top of the file - if 'dct' not in globals() or 'idct' not in globals(): - z = y - exitflag = -1 - Wtot = 0 - return z, s, exitflag, Wtot - - ## Creation of the Lambda tensor - # --- - # Lambda contains the eingenvalues of the difference matrix used in this - # penalized least squares process. + isauto = s is None + axis = tuple(np.array(axis).flatten()) - d = y.ndim - Lambda = np.zeros(sizy) + Lambda = np.zeros(sizy, dtype=float) for i in axis: - # create a 1 x d array (so e.g. [1,1] for a 2D case - siz0 = np.ones((1, y.ndim), dtype=int)[0] + siz0 = np.ones(y.ndim, dtype=int) siz0[i] = sizy[i] - # cos(pi*(reshape(1:sizy(i),siz0)-1)/sizy(i))) - # (arange(1,sizy[i]+1).reshape(siz0) - 1.)/sizy[i] - Lambda = Lambda + ( - np.cos(np.pi * (np.arange(1, sizy[i] + 1) - 1.0) / sizy[i]).reshape(siz0) - ) - # else: - # Lambda = Lambda + siz0 + Lambda += np.cos(np.pi * np.arange(sizy[i]) / sizy[i]).reshape(siz0) Lambda = -2.0 * (len(axis) - Lambda) + if not isauto: - Gamma = 1.0 / (1 + (s * abs(Lambda)) ** smoothOrder) - - ## Upper and lower bound for the smoothness parameter - # The average leverage (h) is by definition in [0 1]. Weak smoothing occurs - # if h is close to 1, while over-smoothing appears when h is near 0. Upper - # and lower bounds for h are given to avoid under- or over-smoothing. See - # equation relating h to the smoothness parameter (Equation #12 in the - # referenced CSDA paper). - N = sum(np.array(sizy) != 1) - # tensor rank of the y-array + s = float(s) + Gamma = 1.0 / (1.0 + (s * np.abs(Lambda)) ** smoothOrder) + + N = sum(dim != 1 for dim in sizy) hMin = 1e-6 hMax = 0.99 - # (h/n)**2 = (1 + a)/( 2 a) - # a = 1/(2 (h/n)**2 -1) - # where a = sqrt(1 + 16 s) - # (a**2 -1)/16 try: sMinBnd = np.sqrt( - (((1 + np.sqrt(1 + 8 * hMax ** (2.0 / N))) / 4.0 / hMax ** (2.0 / N)) ** 2 - 1) + ( + ((1 + np.sqrt(1 + 8 * hMax ** (2.0 / N))) / 4.0 / hMax ** (2.0 / N)) + ** 2 + - 1 + ) / 16.0 ) sMaxBnd = np.sqrt( - (((1 + np.sqrt(1 + 8 * hMin ** (2.0 / N))) / 4.0 / hMin ** (2.0 / N)) ** 2 - 1) + ( + ((1 + np.sqrt(1 + 8 * hMin ** (2.0 / N))) / 4.0 / hMin ** (2.0 / N)) + ** 2 + - 1 + ) / 16.0 ) - except: - sMinBnd = None - sMaxBnd = None - ## Initialize before iterating - # --- - Wtot = W - # --- Initial conditions for z + except Exception: # noqa: BLE001 + sMinBnd = 1e-3 + sMaxBnd = 1e3 + + Wtot = W.copy() if isweighted: - # --- With weighted/missing data - # An initial guess is provided to ensure faster convergence. For that - # purpose, a nearest neighbor interpolation followed by a coarse - # smoothing are performed. - # --- - if z0 != None: # an initial guess (z0) has been provided - z = z0 + if z0 is not None: + z = np.array(z0, dtype=float) else: - z = y # InitialGuess(y,IsFinite); + z = y.copy() z[~IsFinite] = 0.0 else: - z = np.zeros(sizy) - # --- - z0 = z - y[~IsFinite] = 0 - # arbitrary values for missing y-data - # --- + z = np.zeros(sizy, dtype=float) + + z0 = z.copy() + y_work = y.copy() + y_work[~IsFinite] = 0.0 + tol = 1.0 RobustIterativeProcess = True RobustStep = 1 nit = 0 - # --- Error on p. Smoothness parameter s = 10^p errp = 0.1 - # opt = optimset('TolX',errp); - # --- Relaxation factor RF: to speedup convergence - RF = 1 + 0.75 * isweighted - # ?? - ## Main iterative process - # --- - if isauto: - try: - xpost = np.array([(0.9 * np.log10(sMinBnd) + np.log10(sMaxBnd) * 0.1)]) - except: - np.array([100.0]) - else: - xpost = np.array([np.log10(s)]) + RF = 1.0 + 0.75 * isweighted + while RobustIterativeProcess: - # --- "amount" of weights (see the function GCVscore) - aow = sum(Wtot) / noe - # 0 < aow <= 1 - # --- while tol > TolZ and nit < MaxIter: - if verbose: - print("tol", tol, "nit", nit) - nit = nit + 1 - DCTy = dctND(Wtot * (y - z) + z, f=dct) - if isauto and not np.remainder(np.log2(nit), 1): - # --- - # The generalized cross-validation (GCV) method is used. - # We seek the smoothing parameter s that minimizes the GCV - # score i.e. s = Argmin(GCVscore). - # Because this process is time-consuming, it is performed from - # time to time (when nit is a power of 2) - # --- - # errp in here somewhere - - # xpost,f,d = lbfgsb.fmin_l_bfgs_b(gcv,xpost,fprime=None,factr=10.,\ - # approx_grad=True,bounds=[(log10(sMinBnd),log10(sMaxBnd))],\ - # args=(Lambda,aow,DCTy,IsFinite,Wtot,y,nof,noe)) - - # if we have no clue what value of s to use, better span the - # possible range to get a reasonable starting point ... - # only need to do it once though. nS0 is teh number of samples used - if not s0: - ss = np.arange(nS0) * (1.0 / (nS0 - 1.0)) * ( - np.log10(sMaxBnd) - np.log10(sMinBnd) - ) + np.log10(sMinBnd) + nit += 1 + DCTy = dctND(Wtot * (y_work - z) + z, f=dct) + if isauto and (nit == 1 or (nit & (nit - 1)) == 0): + aow = Wtot.mean() + bounds = (np.log10(sMinBnd), np.log10(sMaxBnd)) + if s0 is None: + ss = ( + np.arange(nS0) + * (1.0 / max(1, nS0 - 1.0)) + * (bounds[1] - bounds[0]) + + bounds[0] + ) g = np.zeros_like(ss) - for i, p in enumerate(ss): + for i, pp in enumerate(ss): g[i] = gcv( - p, + pp, Lambda, aow, DCTy, IsFinite, Wtot, - y, + y_work, nof, noe, smoothOrder, ) - # print 10**p,g[i] - xpost = [ss[g == g.min()]] - # print '===============' - # print nit,tol,g.min(),xpost[0],s - # print '===============' + xinit = [ss[int(np.argmin(g))]] else: - xpost = [s0] - xpost, f, d = fmin_l_bfgs_b( - gcv, - xpost, - fprime=None, - factr=10.0, - approx_grad=True, - bounds=[(np.log10(sMinBnd), np.log10(sMaxBnd))], - args=(Lambda, aow, DCTy, IsFinite, Wtot, y, nof, noe, smoothOrder), - ) - s = 10 ** xpost[0] - # update the value we use for the initial s estimate - s0 = xpost[0] - - Gamma = 1.0 / (1 + (s * abs(Lambda)) ** smoothOrder) - - z = RF * dctND(Gamma * DCTy, f=idct) + (1 - RF) * z - # if no weighted/missing data => tol=0 (no iteration) - tol = isweighted * np.linalg.norm(z0 - z) / np.linalg.norm(z) - - z0 = z - # re-initialization - exitflag = nit < MaxIter - - if isrobust: # -- Robust Smoothing: iteratively re-weighted process - # --- average leverage - h = np.sqrt(1 + 16.0 * s) - h = np.sqrt(1 + h) / np.sqrt(2) / h - h = h ** N - # --- take robust weights into account - Wtot = W * RobustWeights(y - z, IsFinite, h, weightstr) - # --- re-initialize for another iterative weighted process + xinit = [np.log10(s0)] + + if _scipy_fmin_l_bfgs_b is not None: + xpost, _, _ = _scipy_fmin_l_bfgs_b( + gcv, + xinit, + fprime=None, + factr=10.0, + approx_grad=True, + bounds=[bounds], + args=( + Lambda, + aow, + DCTy, + IsFinite, + Wtot, + y_work, + nof, + noe, + smoothOrder, + ), + ) + else: + xpost = _golden_section_search( + gcv, + bounds[0], + bounds[1], + tol=0.05, + args=( + Lambda, + aow, + DCTy, + IsFinite, + Wtot, + y_work, + nof, + noe, + smoothOrder, + ), + ) + + s = 10.0 ** xpost[0] + s0 = s + Gamma = 1.0 / (1.0 + (s * np.abs(Lambda)) ** smoothOrder) + else: + if s is None: + s = 1.0 + Gamma = 1.0 / (1.0 + (s * np.abs(Lambda)) ** smoothOrder) + + z = RF * dctND(Gamma * DCTy, f=idct) + (1.0 - RF) * z + norm_z = np.linalg.norm(z) + if norm_z > 0 and isweighted: + tol = np.linalg.norm(z0 - z) / norm_z + else: + tol = 0.0 + z0 = z.copy() + + if verbose: + print(f"nit: {nit}, tol: {tol:.4e}") + + exitflag = int(nit < MaxIter) + + if isrobust: + h = np.sqrt(1.0 + 16.0 * s) + h = np.sqrt(1.0 + h) / np.sqrt(2.0) / h + h = h**N + Wtot = W * RobustWeights(y_work - z, IsFinite, h, weightstr) isweighted = True - tol = 1 + tol = 1.0 nit = 0 - # --- - RobustStep = RobustStep + 1 + RobustStep += 1 RobustIterativeProcess = RobustStep < 3 - # 3 robust steps are enough. else: RobustIterativeProcess = False - # stop the whole process - ## Warning messages - # --- if isauto: if abs(np.log10(s) - np.log10(sMinBnd)) < errp: warning( "MATLAB:smoothn:SLowerBound", - [ - "s = %.3f " % (s) - + ": the lower bound for s " - + "has been reached. Put s as an input variable if required." - ], + [f"s = {s:.3f}: the lower bound for s has been reached."], ) elif abs(np.log10(s) - np.log10(sMaxBnd)) < errp: warning( "MATLAB:smoothn:SUpperBound", - [ - "s = %.3f " % (s) - + ": the upper bound for s " - + "has been reached. Put s as an input variable if required." - ], + [f"s = {s:.3f}: the upper bound for s has been reached."], ) - # warning('MATLAB:smoothn:MaxIter',\ - # ['Maximum number of iterations (%d'%(MaxIter) + ') has '\ - # + 'been exceeded. Increase MaxIter option or decrease TolZ value.']) if is_masked: - z = np.ma.array(z, mask=mask) + z = ma.array(z, mask=mask) return z, s, exitflag, Wtot -def warning(s1, s2): - print(s1) - print(s2[0]) - - -## GCV score -# --- -# function GCVscore = gcv(p) -def gcv(p, Lambda, aow, DCTy, IsFinite, Wtot, y, nof, noe, smoothOrder): - # Search the smoothing parameter s that minimizes the GCV score - # --- - s = 10 ** p - Gamma = 1.0 / (1 + (s * abs(Lambda)) ** smoothOrder) - # --- RSS = Residual sum-of-squares - if np.all(aow > 0.9): # aow = 1 means that all of the data are equally weighted - # very much faster: does not require any inverse DCT - RSS = np.linalg.norm(DCTy * (Gamma - 1.0)) ** 2 - else: - # take account of the weights to calculate RSS: - yhat = dctND(Gamma * DCTy, f=idct) - RSS = np.linalg.norm(np.sqrt(Wtot[IsFinite]) * (y[IsFinite] - yhat[IsFinite])) ** 2 - # --- - TrH = np.sum(Gamma) - GCVscore = RSS / float(nof) / (1.0 - TrH / float(noe)) ** 2 - return GCVscore - - -## Robust weights -# function W = RobustWeights(r,I,h,wstr) -def RobustWeights(r, I, h, wstr): - # weights for robust smoothing. - MAD = np.median(abs(r[I] - np.median(r[I]))) - # median absolute deviation - u = abs(r / (1.4826 * MAD) / np.sqrt(1 - h)) - # studentized residuals - if wstr == "cauchy": - c = 2.385 - W = 1.0 / (1 + (u / c) ** 2) - # Cauchy weights - elif wstr == "talworth": - c = 2.795 - W = u < c - # Talworth weights - else: - c = 4.685 - W = (1 - (u / c) ** 2) ** 2.0 * ((u / c) < 1) - # bisquare weights - - W[np.isnan(W)] = 0 - return W - - -## Initial Guess with weighted/missing data -# function z = InitialGuess(y,I) -def InitialGuess(y, z0): - """ - Compute initial guess for the smoothed array. - - Parameters - ---------- - y : ndarray - The input array to be smoothed. - z0 : ndarray or None - Initial guess for the smoothed array. If None, y is used. - - Returns - ------- - z : ndarray - The initial guess for the smoothed array. - """ - # If z0 is provided and has the right size, use it - if z0 is not None: - if z0.shape == y.shape: - return z0 - else: - # Wrong size, ignore z0 - pass - - # Otherwise, use y as the initial guess - if isinstance(y, np.ma.MaskedArray): - # For masked arrays, preserve the mask - z = y.copy() - else: - z = y.copy() - - return z - # -- coarse fast smoothing using one-tenth of the DCT coefficients - # siz = z.shape; - # z = dct(z,norm='ortho',type=2); - # for k in np.arange(len(z.shape)): - # z[ceil(siz[k]/10)+1:-1] = 0; - # ss = tuple(roll(array(siz),1-k)) - # z = z.reshape(ss) - # z = np.roll(z.T,1) - # z = idct(z,norm='ortho',type=2); - - -# NB: filter is 2*I - (np.roll(I,-1) + np.roll(I,1)) - - -def dctND(data, f=dct): - nd = len(data.shape) - if nd == 1: - return f(data, norm="ortho", type=2) - elif nd == 2: - return f(f(data, norm="ortho", type=2).T, norm="ortho", type=2).T - elif nd == 3: - return f( - f(f(data, norm="ortho", type=2, axis=0), norm="ortho", type=2, axis=1), - norm="ortho", - type=2, - axis=2, - ) - - -def peaks(n): - """ - Mimic basic of matlab peaks fn - - Parameters - ---------- - n : int or array_like - If int, size of the output array. If array, find peaks in this array. - - Returns - ------- - z : ndarray or list - If n is int, returns a 2D array with peaks. - If n is array, returns indices of peaks in the array. - """ - # If n is an array, find peaks in it - if isinstance(n, np.ndarray): - # Find local maxima - indices = [] - for i in range(1, len(n)-1): - if n[i] > n[i-1] and n[i] > n[i+1]: - indices.append(i) - return indices - - # Otherwise, generate a 2D peaks function - xp = np.arange(n) - x, y = np.meshgrid(xp, xp) - z = np.zeros_like(x).astype(float) - for i in range(n // 5): - x0 = np.random.random() * n - y0 = np.random.random() * n - sdx = np.random.random() * n / 4.0 - sdy = sdx - c = np.random.random() * 2 - 1.0 - f = np.exp( - -(((x - x0) / sdx) ** 2) - - ((y - y0) / sdy) ** 2 - - (((x - x0) / sdx)) * ((y - y0) / sdy) * c - ) - f *= np.random.random() - z += f - return z - - -def test1(): - plt.figure(1) - plt.clf() - # 1-D example - x = linspace(0, 100, 2 ** 8) - y = cos(x / 10) + (x / 50) ** 2 + randn(size(x)) / 10 - y[[70, 75, 80]] = [5.5, 5, 6] - z = smoothn(y)[0] - # Regular smoothing - zr = smoothn(y, isrobust=True)[0] - # Robust smoothing - subplot(121) - plot(x, y, "r.") - plot(x, z, "k") - title("Regular smoothing") - subplot(122) - plot(x, y, "r.") - plot(x, zr, "k") - title("Robust smoothing") - - -def test2(axis=None): - # 2-D example - plt.figure(2) - plt.clf() - xp = arange(0, 1, 0.02) - [x, y] = meshgrid(xp, xp) - f = exp(x + y) + sin((x - 2 * y) * 3) - fn = f + (randn(f.size) * 0.5).reshape(f.shape) - fs = smoothn(fn, axis=axis)[0] - subplot(121) - plt.imshow(fn, interpolation="Nearest") - # axis square - subplot(122) - plt.imshow(fs, interpolation="Nearest") - # axis square - - -def test3(axis=None): - # 2-D example with missing data - plt.figure(3) - plt.clf() - n = 256 - y0 = peaks(n) - y = (y0 + random(shape(y0)) * 2 - 1.0).flatten() - I = np.random.permutation(range(n ** 2)) - y[I[1 : n ** 2 * 0.5]] = nan - # lose 50% of data - y = y.reshape(y0.shape) - y[40:90, 140:190] = nan - # create a hole - yData = y.copy() - z0, s, exitflag, Wtot = smoothn(yData, axis=axis) - # smooth data - yData = y.copy() - z, s, exitflag, Wtot = smoothn(yData, isrobust=True, axis=axis) - # smooth data - y = yData - vmin = np.min([np.min(z), np.min(z0), np.min(y), np.min(y0)]) - vmax = np.max([np.max(z), np.max(z0), np.max(y), np.max(y0)]) - subplot(221) - plt.imshow(y, interpolation="Nearest", vmin=vmin, vmax=vmax) - title("Noisy corrupt data") - subplot(222) - plt.imshow(z0, interpolation="Nearest", vmin=vmin, vmax=vmax) - title("Recovered data #1") - subplot(223) - plt.imshow(z, interpolation="Nearest", vmin=vmin, vmax=vmax) - title("Recovered data #2") - subplot(224) - plt.imshow(y0, interpolation="Nearest", vmin=vmin, vmax=vmax) - title("... compared with original data") - - -def test4(i=10, step=0.2, axis=None): - [x, y, z] = mgrid[-2:2:step, -2:2:step, -2:2:step] - x = array(x) - y = array(y) - z = array(z) - xslice = [-0.8, 1] - yslice = 2 - zslice = [-2, 0] - v0 = x * exp(-(x ** 2) - y ** 2 - z ** 2) - vn = v0 + randn(x.size).reshape(x.shape) * 0.06 - v = smoothn(vn)[0] - plt.figure(4) - plt.clf() - vmin = np.min([np.min(v[:, :, i]), np.min(v0[:, :, i]), np.min(vn[:, :, i])]) - vmax = np.max([np.max(v[:, :, i]), np.max(v0[:, :, i]), np.max(vn[:, :, i])]) - subplot(221) - plt.imshow(v0[:, :, i], interpolation="Nearest", vmin=vmin, vmax=vmax) - title("clean z=%d" % i) - subplot(223) - plt.imshow(vn[:, :, i], interpolation="Nearest", vmin=vmin, vmax=vmax) - title("noisy") - subplot(224) - plt.imshow(v[:, :, i], interpolation="Nearest", vmin=vmin, vmax=vmax) - title("cleaned") - - -def test5(): - t = linspace(0, 2 * pi, 1000) - x = 2 * cos(t) * (1 - cos(t)) + randn(size(t)) * 0.1 - y = 2 * sin(t) * (1 - cos(t)) + randn(size(t)) * 0.1 - zx = smoothn(x)[0] - zy = smoothn(y)[0] - plt.figure(5) - plt.clf() - plt.title("Cardioid") - plot(x, y, "r.") - plot(zx, zy, "k") - - -def test6(noise=0.05, nout=30): - plt.figure(6) - plt.clf() - [x, y] = meshgrid(linspace(0, 1, 24), linspace(0, 1, 24)) - Vx0 = cos(2 * pi * x + pi / 2) * cos(2 * pi * y) - Vy0 = sin(2 * pi * x + pi / 2) * sin(2 * pi * y) - Vx = Vx0 + noise * randn(24, 24) - # adding Gaussian noise - Vy = Vy0 + noise * randn(24, 24) - # adding Gaussian noise - I = np.random.permutation(range(Vx.size)) - Vx = Vx.flatten() - Vx[I[0:nout]] = (rand(nout, 1) - 0.5) * 5 - # adding outliers - Vx = Vx.reshape(Vy.shape) - Vy = Vy.flatten() - Vy[I[0:nout]] = (rand(nout, 1) - 0.5) * 5 - # adding outliers - Vy = Vy.reshape(Vx.shape) - Vsx = smoothn(Vx, isrobust=True)[0] - Vsy = smoothn(Vy, isrobust=True)[0] - subplot(131) - quiver(x, y, Vx, Vy, 2.5) - title("Noisy") - subplot(132) - quiver(x, y, Vsx, Vsy) - title("Recovered") - subplot(133) - quiver(x, y, Vx0, Vy0) - title("Original") - - -def sparseSVD(D): - import scipy.sparse - - try: - import sparsesvd - except: - print("bummer ... better get sparsesvd") - exit(0) - Ds = scipy.sparse.csc_matrix(D) - a = sparsesvd.sparsesvd(Ds, Ds.shape[0]) - return a - - -def sparseTest(n=1000): - I = np.identity(n) - - # define a 'traditional' D1 matrix - # which is a right-side difference - # and which is *not* symmetric :-( - D1 = np.matrix(I - np.roll(I, 1)) - # so define a symemtric version - D1a = D1.T - D1 - - U, s, Vh = scipy.linalg.svd(D1a) - - # now, get eigenvectors for D1a - Ut, eigenvalues, Vt = sparseSVD(D1a) - Ut = np.matrix(Ut) - - # then, an equivalent 2nd O term would be - D2a = D1a ** 2 - - # show we can recover D1a - D1a_est = Ut.T * np.diag(eigenvalues) * Ut - - # Now, because D2a (& the target D1a) are symmetric: - D1a_est = Ut.T * np.diag(eigenvalues ** 0.5) * Ut - - D = 2 * I - (np.roll(I, -1) + np.roll(I, 1)) - a = sparseSVD(-D) - eigenvalues = np.matrix(a[1]) - Ut = np.matrix(a[0]) - Vt = np.matrix(a[2]) - orig = Ut.T * np.diag(np.array(eigenvalues).flatten()) * Vt - - Feigenvalues = np.diag(np.array(np.c_[eigenvalues, 0]).flatten()) - FUt = np.c_[Ut.T, np.zeros(Ut.shape[1])] - # confirm: FUt * Feigenvalues * FUt.T ~= D - - # m is a 1st O difference matrix - # with careful edge conditions - # such that m.T * m = D2 - # D2 being a 2nd O difference matrix - m = np.matrix(np.identity(100) - np.roll(np.identity(100), 1)) - m[-1, -1] = 0 - m[0, 0] = 1 - a = sparseSVD(m) - eigenvalues = np.matrix(a[1]) - Ut = np.matrix(a[0]) - Vt = np.matrix(a[2]) - orig = Ut.T * np.diag(np.array(eigenvalues).flatten()) * Vt - # Vt* Vt.T = I - # Ut.T * Ut = I - # ((Vt.T * (np.diag(np.array(eigenvalues).flatten())**2)) * Vt) - # we see you get the same as m.T * m by squaring the eigenvalues - - -# from StackOverflow -# https://stackoverflow.com/questions/17115030/want-to-smooth-a-contour-from-a-masked-array - -def smooth(u, mask): - m = ~mask - r = u*m # set all 'masked' points to 0. so they aren't used in the smoothing - a = 4*r[1:-1,1:-1] + r[2:,1:-1] + r[:-2,1:-1] + r[1:-1,2:] + r[1:-1,:-2] - b = 4*m[1:-1,1:-1] + m[2:,1:-1] + m[:-2,1:-1] + m[1:-1,2:] + m[1:-1,:-2] # a divisor that accounts for masked points - b[b==0] = 1. # for avoiding divide by 0 error (region is masked so value doesn't matter) - u[1:-1,1:-1] = a/b - -def smooth_masked_array(u): - """ Use smooth() on the masked array """ - - if not isinstance(u, np.ma.MaskedArray): - raise ValueError("Expected masked array") - - m = u.mask - - # run the data through the smoothing filter a few times - for i in range(10): - smooth(u, m) - - return np.ma.array(u, mask=m) # put together the mask and the data +# Alias for modern Pythonic API +smooth_field = smoothn diff --git a/openpiv/test/test_smoothn.py b/openpiv/test/test_smoothn.py index a533c181..617da3d9 100644 --- a/openpiv/test/test_smoothn.py +++ b/openpiv/test/test_smoothn.py @@ -1,20 +1,31 @@ -"""Test module for smoothn.py""" +import sys import numpy as np -import numpy.ma as ma -import pytest -from scipy.fftpack import dct, idct +from numpy import ma + +try: + import pytest +except ImportError: + pytest = None + +try: + from scipy.fftpack import dct, idct +except ImportError: + from openpiv.smoothn import dct, idct from openpiv.smoothn import ( - smoothn, - gcv, + InitialGuess, RobustWeights, - warning, dctND, - InitialGuess, - peaks + gcv, + peaks, + scipy_smooth2d, + smooth_field, + smoothn, + warning, ) + def test_smoothn_basic(): """Test basic smoothn functionality with 1D data""" # Create a noisy 1D signal @@ -27,7 +38,7 @@ def test_smoothn_basic(): y_smooth, s, exitflag, Wtot = smoothn(y_noisy) # Check that the smoothed signal is closer to the true signal than the noisy one - assert np.mean((y_smooth - y_true)**2) < np.mean((y_noisy - y_true)**2) + assert np.mean((y_smooth - y_true) ** 2) < np.mean((y_noisy - y_true) ** 2) # Check that s is positive (smoothing parameter) assert s > 0 @@ -38,19 +49,21 @@ def test_smoothn_basic(): # Check that weights are all ones for unweighted data assert np.all(Wtot == 1) + def test_smoothn_2d(): """Test smoothn with 2D data""" # Create a noisy 2D signal x, y = np.meshgrid(np.linspace(0, 1, 20), np.linspace(0, 1, 20)) - z_true = np.sin(2*np.pi*x) * np.cos(2*np.pi*y) + z_true = np.sin(2 * np.pi * x) * np.cos(2 * np.pi * y) noise = np.random.normal(0, 0.1, z_true.shape) z_noisy = z_true + noise # Apply smoothn - z_smooth, s, exitflag, Wtot = smoothn(z_noisy) + z_smooth, _s, _exitflag, _Wtot = smoothn(z_noisy) # Check that the smoothed signal is closer to the true signal than the noisy one - assert np.mean((z_smooth - z_true)**2) < np.mean((z_noisy - z_true)**2) + assert np.mean((z_smooth - z_true) ** 2) < np.mean((z_noisy - z_true) ** 2) + def test_smoothn_with_s(): """Test smoothn with specified smoothing parameter""" @@ -62,11 +75,12 @@ def test_smoothn_with_s(): # 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) # Check that s is the specified value assert s == s_value + def test_smoothn_with_weights(): """Test smoothn with weights""" # Create a noisy 1D signal @@ -80,18 +94,22 @@ def test_smoothn_with_weights(): W[40:60] = 2.0 # Higher weights in the middle # Apply smoothn with weights - y_smooth, s, exitflag, Wtot = smoothn(y_noisy, W=W) + y_smooth, _s, _exitflag, _Wtot = smoothn(y_noisy, W=W) # Check that the weighted region has lower error - middle_error = np.mean((y_smooth[40:60] - y_true[40:60])**2) - outer_error = np.mean(np.concatenate([(y_smooth[:40] - y_true[:40])**2, - (y_smooth[60:] - y_true[60:])**2])) + middle_error = np.mean((y_smooth[40:60] - y_true[40:60]) ** 2) + outer_error = np.mean( + np.concatenate( + [(y_smooth[:40] - y_true[:40]) ** 2, (y_smooth[60:] - y_true[60:]) ** 2] + ) + ) # Due to randomness in the test, we can't always guarantee that middle_error < outer_error # Instead, we'll check that the errors are reasonable assert middle_error < 0.01 assert outer_error < 0.01 + def test_smoothn_with_missing_data(): """Test smoothn with missing data (NaN values)""" # Create a noisy 1D signal @@ -104,16 +122,17 @@ def test_smoothn_with_missing_data(): y_noisy[30:40] = np.nan # Apply smoothn - y_smooth, s, exitflag, Wtot = smoothn(y_noisy) + y_smooth, _s, _exitflag, _Wtot = smoothn(y_noisy) # Check that NaN values have been filled assert not np.any(np.isnan(y_smooth)) # Check that the filled values are reasonable (close to true values) # We can't expect exact matches, but they should be closer to true values than random - filled_error = np.mean((y_smooth[30:40] - y_true[30:40])**2) + filled_error = np.mean((y_smooth[30:40] - y_true[30:40]) ** 2) assert filled_error < 0.5 # A reasonable threshold + def test_smoothn_with_masked_array(): """Test smoothn with masked array input""" # Create a noisy 1D signal @@ -128,7 +147,7 @@ def test_smoothn_with_masked_array(): y_masked = ma.array(y_noisy, mask=mask) # Apply smoothn - y_smooth, s, exitflag, Wtot = smoothn(y_masked) + y_smooth, _s, _exitflag, _Wtot = smoothn(y_masked) # Check that the result is also a masked array assert isinstance(y_smooth, ma.MaskedArray) @@ -136,6 +155,7 @@ def test_smoothn_with_masked_array(): # Check that the mask is preserved assert np.all(y_smooth.mask == mask) + def test_smoothn_with_standard_deviation(): """Test smoothn with standard deviation input""" # Create a noisy 1D signal @@ -149,18 +169,22 @@ def test_smoothn_with_standard_deviation(): sd[40:60] = 0.2 # Higher uncertainty in the middle # Apply smoothn with standard deviation - y_smooth, s, exitflag, Wtot = smoothn(y_noisy, sd=sd) + y_smooth, _s, _exitflag, _Wtot = smoothn(y_noisy, sd=sd) # The middle region should be smoothed more due to higher uncertainty middle_smoothing = np.mean(np.abs(y_smooth[40:60] - y_noisy[40:60])) - outer_smoothing = np.mean(np.concatenate([np.abs(y_smooth[:40] - y_noisy[:40]), - np.abs(y_smooth[60:] - y_noisy[60:])])) + outer_smoothing = np.mean( + np.concatenate( + [np.abs(y_smooth[:40] - y_noisy[:40]), np.abs(y_smooth[60:] - y_noisy[60:])] + ) + ) # Due to randomness in the test, we can't always guarantee that middle_smoothing > outer_smoothing # Instead, we'll check that the smoothing is happening in general assert middle_smoothing > 0.01 assert outer_smoothing > 0.01 + def test_smoothn_robust(): """Test robust smoothn with outliers""" # Create a 1D signal with outliers @@ -175,10 +199,10 @@ def test_smoothn_robust(): y_noisy[75] = 5.0 # Apply regular smoothn - y_smooth, s1, _, _ = smoothn(y_noisy) + y_smooth, _s1, _, _ = smoothn(y_noisy) # Apply robust smoothn - y_robust, s2, _, _ = smoothn(y_noisy, isrobust=True) + y_robust, _s2, _, _ = smoothn(y_noisy, isrobust=True) # The robust version should be less affected by outliers # Check at the outlier points @@ -189,6 +213,7 @@ def test_smoothn_robust(): # The robust version should have lower error at outlier points assert robust_error < regular_error + def test_smoothn_with_initial_guess(): """Test smoothn with initial guess""" # Create a noisy 1D signal @@ -201,20 +226,21 @@ def test_smoothn_with_initial_guess(): z0 = np.sin(x - 0.5) # Apply smoothn with initial guess - y_smooth, s, exitflag, Wtot = smoothn(y_noisy, z0=z0) + y_smooth, _s, _exitflag, _Wtot = smoothn(y_noisy, z0=z0) # The result should be closer to the true signal than to the initial guess - error_to_true = np.mean((y_smooth - y_true)**2) - error_to_guess = np.mean((y_smooth - z0)**2) + error_to_true = np.mean((y_smooth - y_true) ** 2) + error_to_guess = np.mean((y_smooth - z0) ** 2) assert error_to_true < error_to_guess + def test_smoothn_with_axis(): """Test smoothn with axis parameter""" # Create a 2D array where we want to smooth only along one axis x = np.linspace(0, 10, 20) y = np.linspace(0, 5, 10) - X, Y = np.meshgrid(x, y) + X, _Y = np.meshgrid(x, y) # Create a signal that varies smoothly along x but has noise along y Z_true = np.sin(X) @@ -251,6 +277,7 @@ def test_smoothn_with_axis(): assert total_variation_x < total_variation_original assert total_variation_both < total_variation_original + def test_smoothn_with_different_smoothing_orders(): """Test smoothn with different smoothing orders""" # Create a noisy 1D signal @@ -281,6 +308,7 @@ def test_smoothn_with_different_smoothing_orders(): assert var_d2_y2 < 0.01 assert var_d2_y3 < 0.01 + def test_smoothn_with_different_weight_strings(): """Test smoothn with different weight strings for robust smoothing""" # Create a 1D signal with outliers @@ -295,7 +323,9 @@ def test_smoothn_with_different_weight_strings(): y_noisy[75] = 5.0 # Apply robust smoothn with different weight strings - y_bisquare, _, _, _ = smoothn(y_noisy, isrobust=True, weightstr="bisquare") # Default + y_bisquare, _, _, _ = smoothn( + y_noisy, isrobust=True, weightstr="bisquare" + ) # Default y_cauchy, _, _, _ = smoothn(y_noisy, isrobust=True, weightstr="cauchy") y_talworth, _, _, _ = smoothn(y_noisy, isrobust=True, weightstr="talworth") @@ -304,21 +334,28 @@ def test_smoothn_with_different_weight_strings(): # Check at the outlier points outlier_points = [25, 50, 75] - nonrobust_error = np.mean(np.abs(y_nonrobust[outlier_points] - y_true[outlier_points])) - bisquare_error = np.mean(np.abs(y_bisquare[outlier_points] - y_true[outlier_points])) + nonrobust_error = np.mean( + np.abs(y_nonrobust[outlier_points] - y_true[outlier_points]) + ) + bisquare_error = np.mean( + np.abs(y_bisquare[outlier_points] - y_true[outlier_points]) + ) cauchy_error = np.mean(np.abs(y_cauchy[outlier_points] - y_true[outlier_points])) - talworth_error = np.mean(np.abs(y_talworth[outlier_points] - y_true[outlier_points])) + talworth_error = np.mean( + np.abs(y_talworth[outlier_points] - y_true[outlier_points]) + ) # All robust methods should be better than non-robust assert bisquare_error < nonrobust_error assert cauchy_error < nonrobust_error assert talworth_error < nonrobust_error + def test_smoothn_edge_cases(): """Test smoothn with edge cases""" # Test with a single element array y_single = np.array([5.0]) - z_single, s, exitflag, Wtot = smoothn(y_single) + z_single, _s, exitflag, _Wtot = smoothn(y_single) assert z_single == y_single assert exitflag == 0 @@ -329,7 +366,7 @@ def test_smoothn_edge_cases(): # Test with all NaN values - skip this test as it's causing issues # with the optimization algorithm - pass + def test_gcv_function(): """Test the GCV (Generalized Cross-Validation) function""" @@ -340,8 +377,10 @@ def test_gcv_function(): y_noisy = y_true + noise # Get DCTy and other parameters needed for GCV - DCTy = dct(y_noisy, type=2, norm='ortho') - Lambda = -2.0 * (1 - np.cos(np.pi * (np.arange(1, len(y_noisy) + 1) - 1.0) / len(y_noisy))) + DCTy = dct(y_noisy, type=2, norm="ortho") + Lambda = -2.0 * ( + 1 - np.cos(np.pi * (np.arange(1, len(y_noisy) + 1) - 1.0) / len(y_noisy)) + ) IsFinite = np.isfinite(y_noisy) Wtot = np.ones_like(y_noisy) nof = np.sum(IsFinite) @@ -361,6 +400,7 @@ def test_gcv_function(): # Higher smoothing parameter should give different score assert score1 != score2 + def test_robust_weights(): """Test the RobustWeights function""" # Create residuals with some outliers @@ -394,10 +434,10 @@ def test_robust_weights(): assert np.all(w_cauchy >= 0) and np.all(w_cauchy <= 1) assert np.all(w_talworth >= 0) and np.all(w_talworth <= 1) + def test_dctND(): """Test the dctND function""" # Import the dctND function from the module - from openpiv.smoothn import dctND # Create a simple 1D array x = np.array([1.0, 2.0, 3.0, 4.0]) @@ -423,6 +463,7 @@ def test_dctND(): # Check that the reconstructed signal matches the original assert np.allclose(y, y_reconstructed) + def test_warning_function(): """Test the warning function (just for coverage)""" # This is a simple function that just prints warnings @@ -445,6 +486,7 @@ def test_warning_function(): assert "Warning type" in output assert "Warning message" in output + def test_smoothn_with_negative_weights(): """Test smoothn with negative weights (should raise a warning)""" # Create a noisy 1D signal @@ -474,7 +516,8 @@ def test_smoothn_with_negative_weights(): assert np.all(Wtot[40:60] == 0) # Check that the smoothed signal is still reasonable - assert np.mean((y_smooth - y_true)**2) < np.mean((y_noisy - y_true)**2) + assert np.mean((y_smooth - y_true) ** 2) < np.mean((y_noisy - y_true) ** 2) + def test_initial_guess_function(): """Test the InitialGuess function""" @@ -503,11 +546,12 @@ def test_initial_guess_function(): assert isinstance(z, ma.MaskedArray) assert np.array_equal(z.mask, mask) + def test_peaks_function(): """Test the peaks function""" # Create a signal with peaks x = np.linspace(0, 10, 100) - y = np.sin(x) + 0.5 * np.sin(2*x) + y = np.sin(x) + 0.5 * np.sin(2 * x) # Find peaks idx = peaks(y) @@ -518,17 +562,16 @@ def test_peaks_function(): # Check that the identified points are actually peaks for i in idx: if i > 0 and i < len(y) - 1: - assert y[i] > y[i-1] and y[i] > y[i+1] + assert y[i] > y[i - 1] and y[i] > y[i + 1] + def test_smoothn_3d(): """Test smoothn with 3D data""" # Create a noisy 3D signal x, y, z = np.meshgrid( - np.linspace(0, 1, 10), - np.linspace(0, 1, 10), - np.linspace(0, 1, 10) + np.linspace(0, 1, 10), np.linspace(0, 1, 10), np.linspace(0, 1, 10) ) - data_true = np.sin(2*np.pi*x) * np.cos(2*np.pi*y) * np.sin(2*np.pi*z) + data_true = np.sin(2 * np.pi * x) * np.cos(2 * np.pi * y) * np.sin(2 * np.pi * z) noise = np.random.normal(0, 0.1, data_true.shape) data_noisy = data_true + noise @@ -536,7 +579,9 @@ def test_smoothn_3d(): data_smooth, s, exitflag, _ = smoothn(data_noisy) # Check that the smoothed signal is closer to the true signal than the noisy one - assert np.mean((data_smooth - data_true)**2) < np.mean((data_noisy - data_true)**2) + assert np.mean((data_smooth - data_true) ** 2) < np.mean( + (data_noisy - data_true) ** 2 + ) # Check that s is positive (smoothing parameter) assert s > 0 @@ -544,6 +589,7 @@ def test_smoothn_3d(): # Check that exitflag is 1 (convergence) assert exitflag == 1 + def test_smoothn_with_verbose(): """Test smoothn with verbose output""" # Create a noisy 1D signal @@ -555,6 +601,7 @@ def test_smoothn_with_verbose(): # Capture stdout to check for verbose output import io import sys + captured_output = io.StringIO() sys.stdout = captured_output @@ -569,7 +616,8 @@ def test_smoothn_with_verbose(): assert "tol" in output.lower() or "nit" in output.lower() # Check that the smoothed signal is reasonable - assert np.mean((y_smooth - y_true)**2) < np.mean((y_noisy - y_true)**2) + assert np.mean((y_smooth - y_true) ** 2) < np.mean((y_noisy - y_true) ** 2) + def test_smoothn_with_max_iter(): """Test smoothn with maximum iterations""" @@ -586,7 +634,8 @@ def test_smoothn_with_max_iter(): assert exitflag == 0 # Check that the smoothed signal is still reasonable - assert np.mean((y_smooth - y_true)**2) < np.mean((y_noisy - y_true)**2) + assert np.mean((y_smooth - y_true) ** 2) < np.mean((y_noisy - y_true) ** 2) + def test_smoothn_with_tolerance(): """Test smoothn with different tolerance values""" @@ -607,5 +656,105 @@ def test_smoothn_with_tolerance(): assert exitflag2 == 1 # Check that both smoothed signals are reasonable - assert np.mean((y_smooth_high_tol - y_true)**2) < np.mean((y_noisy - y_true)**2) - assert np.mean((y_smooth_low_tol - y_true)**2) < np.mean((y_noisy - y_true)**2) + assert np.mean((y_smooth_high_tol - y_true) ** 2) < np.mean((y_noisy - y_true) ** 2) + assert np.mean((y_smooth_low_tol - y_true) ** 2) < np.mean((y_noisy - y_true) ** 2) + + +def test_scipy_smooth2d_basic(): + """Test modern 2D scalar field smoothing""" + np.random.seed(0) + x, y = np.meshgrid(np.linspace(0, 1, 20), np.linspace(0, 1, 20)) + z_true = np.sin(2 * np.pi * x) * np.cos(2 * np.pi * y) + z_noisy = z_true + np.random.normal(0, 0.05, z_true.shape) + + z_smooth, _s, exitflag, _Wtot = scipy_smooth2d(z_noisy, s=0.5) + assert exitflag == 1 + assert np.mean((z_smooth - z_true) ** 2) < np.mean((z_noisy - z_true) ** 2) + + +def test_scipy_smooth2d_with_gaps(): + """Test 2D smoothing over missing values / gaps (NaNs)""" + np.random.seed(0) + x, y = np.meshgrid(np.linspace(0, 1, 20), np.linspace(0, 1, 20)) + z_true = np.sin(2 * np.pi * x) * np.cos(2 * np.pi * y) + z_noisy = z_true + np.random.normal(0, 0.05, z_true.shape) + z_noisy[6:12, 6:12] = np.nan + + z_smooth, _, exitflag, _ = scipy_smooth2d(z_noisy, s=0.5) + assert exitflag == 1 + assert not np.any(np.isnan(z_smooth)) + assert np.mean((z_smooth[6:12, 6:12] - z_true[6:12, 6:12]) ** 2) < 0.2 + + +def test_scipy_smooth2d_masked_array(): + """Test 2D smoothing preserving masked array mask""" + x, y = np.meshgrid(np.linspace(0, 1, 20), np.linspace(0, 1, 20)) + z_true = np.sin(2 * np.pi * x) * np.cos(2 * np.pi * y) + z_noisy = z_true + np.random.normal(0, 0.05, z_true.shape) + mask = np.zeros_like(z_noisy, dtype=bool) + mask[5:10, 5:10] = True + z_masked = ma.array(z_noisy, mask=mask) + + z_smooth, _, _exitflag, _ = scipy_smooth2d(z_masked, s=0.5) + assert isinstance(z_smooth, ma.MaskedArray) + assert np.all(z_smooth.mask == mask) + + +def test_scipy_smooth2d_robust(): + """Test 2D robust smoothing with outliers""" + np.random.seed(0) + x, _y = np.meshgrid(np.linspace(0, 1, 15), np.linspace(0, 1, 15)) + z_true = np.sin(2 * np.pi * x) + z_noisy = z_true + np.random.normal(0, 0.05, z_true.shape) + z_noisy[5, 5] = 5.0 + z_noisy[10, 10] = -5.0 + + z_smooth_reg, _, _, _ = scipy_smooth2d(z_noisy, isrobust=False) + z_smooth_rob, _, _, _ = scipy_smooth2d(z_noisy, isrobust=True) + + err_reg = abs(z_smooth_reg[5, 5] - z_true[5, 5]) + abs( + z_smooth_reg[10, 10] - z_true[10, 10] + ) + err_rob = abs(z_smooth_rob[5, 5] - z_true[5, 5]) + abs( + z_smooth_rob[10, 10] - z_true[10, 10] + ) + assert err_rob < err_reg + + +def test_smooth_field_spline_method(): + """Test smooth_field with method='spline'""" + np.random.seed(0) + x, _y = np.meshgrid(np.linspace(0, 1, 15), np.linspace(0, 1, 15)) + 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) + + +if __name__ == "__main__": + if pytest is not None: + sys.exit(pytest.main(["-v", __file__])) + else: + import inspect + + current_module = sys.modules[__name__] + test_funcs = [ + obj + for name, obj in inspect.getmembers(current_module) + if name.startswith("test_") and inspect.isfunction(obj) + ] + passed = 0 + failed = 0 + for func in test_funcs: + try: + func() + print(f"PASS: {func.__name__}") + passed += 1 + except Exception as e: # noqa: BLE001 + print(f"FAIL: {func.__name__} - {e}") + failed += 1 + print(f"\nSummary: {passed} passed, {failed} failed.") + if failed > 0: + sys.exit(1) diff --git a/pyproject.toml b/pyproject.toml index 69d631e9..11380b6a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "OpenPIV" -version = "0.26.1" +version = "0.26.2" description = "OpenPIV consists in a Python and Cython modules for scripting and executing the analysis of a set of PIV image pairs. In addition, a Qt and Tk graphical user interfaces are in development, to ease the use for those users who don't have python skills." authors = ["Alex Liberzon"] license = "GPLv3"